您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP设计模式之建造者模式

2025/6/11 9:17:29发布24次查看
建造者模式属于创建型模式
概述:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
优点:
建造者模式可以很好的将一个对象的实现与相关的‘业务’逻辑分离开来,从而可以在不改变事件逻辑的前提下,使增加(或改变)实现变得非常容易
缺点:
建造者接口的修改会导致所有执行类的修改
以下情况应该使用建造者:
1 需要生成的产品对象有复杂的内部结构
2 需要生成的产品对象的属性相互依赖,建造者模式可以强迫生成顺序
3 在对象创建过程中会使用到系统中的一些其他对象,这些对象在产品的创建过程中不易得到
使用建造者模式主要有一下效果:
1 建造者模式的使用使得产品的内部表象可以独立的变化,使用建造者模式可以使客户端不必知道产品内部组成的细节
2 每一个builder都相对独立,而与其他的builder无关
3 模式所建造的最终产品更易于控制
class product{
public $type = null;
public $price = null;
public $color = null;
public function settype($type){
$this->type = $type;
}
public function setprice($price){
$this->price = $price;
}
public function setcolor($color){
$this->color = $color;
}
}
$config = array(
'type' => 'shirt',
'price' => 100,
'color' => 'red',
);
// 不使用builder模式
$product = new product();
$product->settype($config['type']);
$product->setprice($config['price']);
$product->setcolor($config['color']);
使用builder模式
/*builder类*/
class productbuilder{
public $config = null;
public $object = null;
public function __construct($config){
$this->object = new product();
$this->config = $config;
}
public function build(){
$this->object->settype($this->config['type']);
$this->object->setprice($this->config['price']);
$this->object->setcolor($this->config['color']);
}
public fuction getproduct(){
return $this->object;
}
}
$objbuilder = new productbuilder($config);
$objbuilder->build();
$objproduct = $objbuilder->getproduct();
var_dump($objproduct);
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product