星际里面有不少的任务关,也可以自己编辑地图,画面上有各种地形,建筑和部队,存在一个问题,初始化画面的流程很乱,待解决的问题:完成初始化画面的工作,同时尽量减少各种绘制细节的耦合.
思路:既然星际的画面由几个部分组成,地图(就是地形和矿产),建筑,部队,那么我们把他们看成是零件,组装起来就是最后的产品(整个画面).
建造器(Builder)模式示例:
- <?php
-
-
-
- interface Builder
-
- {
-
-
-
- public function buildMapPart();
-
-
-
- public function buildBuildingPart();
-
-
-
- public function buildArmyPart();
-
-
-
- public function getResult();
-
- }
-
-
-
- class ConcreteBuilder implements Builder
-
- {
-
-
-
- public function buildMapPart()
-
- {
-
-
-
- echo '地图零件n';
-
- }
-
-
-
- public function buildBuildingPart()
-
- {
-
-
-
- echo '建筑零件n';
-
- }
-
-
-
- public function buildArmyPart()
-
- {
-
-
-
- echo '部队零件n';
-
- }
-
-
-
- public function getResult()
-
- {
-
-
-
- echo '组装零件n';
-
- }
-
- }
-
-
-
- class Director
-
- {
-
-
-
- private $builder;
-
-
-
- public function __construct($builder)
-
- {
-
-
-
- $this->builder = $builder;
-
- }
-
-
-
- public function buildeAllPart()
-
- {
-
-
-
- $this->builder->buildMapPart();
-
-
-
- $this->builder->buildBuildingPart();
-
-
-
- $this->builder->buildArmyPart();
-
- }
-
- }
-
-
-
- $concreteBuilder = new ConcreteBuilder();
-
-
-
- $director = new Director($concreteBuilder);
-
-
-
- $director->buildeAllPart();
-
-
-
- $concreteBuilder->getResult();
-
- ?>
用途总结:建造器模式可以将流程和细节分离,各司其职.
实现总结:需要一个建造器接口或者抽象类,负责规范各个方法,比如上面的Builder,然后让实际的建造器类去实现所有的方法,比如上面的ConcreteBuilder,同时需要负责流程管理的监督类,比如上面的Director,负责调用建造器的各个零件制造方法,最后让建造器去组装所有的零件. |