我们都知道,得到一匹布需要大概这么几步:
1、染色
2、印花
3、裁剪
这种形式在面向对象中怎么实现呢?
面向过程【继承模式】实现:
继承模式得到需要的布料,一步一步的加工。
继承的层次越来越深,扩展性差。如果中间加道其他程序,就有些吃力了。
<?php
header("content-type:text/html;charset=utf8");
class BaseCloth{ //布料初始的样子
protected $content;
public function __construct($con){
$this->content=$con;
}
public function cloth(){
return $this->content;
}
}
class DyeingCloth extends BaseCloth{ //染色
public function dyeing(){
return $this->content." --->染上色";
}
}
class StampCloth extends DyeingCloth{ //印花
public function stamp(){
return $this->content." --->印上好看的花";
}
}
class CutCloth extends StampCloth{ //裁剪
public function cut(){
return $this->content." --->根据需求裁剪";
}
}
//布料加工。
$cloth= new BaseCloth("白布");
$dyeing=new DyeingCloth($cloth->cloth());
$stamp=new StampCloth($dyeing->dyeing());
$cut=new CutCloth($stamp->stamp());
echo $cut->cut();
?>
装饰器模式实现布匹加工。
<?php
header("content-type:text/html;charset=utf8");
/**
* 装饰器模式完成布料的加工。动态、扩展性好。
*/
class BaseCloth{ //布料的初始样子
protected $content;
public function __construct($con){
$this->content=$con;
}
public function cloth(){
return $this->content;
}
}
class DyeingCloth extends BaseCloth{ //染色
public function __construct(BaseCloth $cloth){
$this->cloth=$cloth;
$this->cloth();
}
public function cloth(){
return $this->cloth->cloth()." --->染上色";
}
}
class StampCloth extends BaseCloth{ //印花
public function __construct(BaseCloth $cloth){
$this->cloth=$cloth;
$this->cloth();
}
public function cloth(){
return $this->cloth->cloth()." --->印上花";
}
}
class CutCloth extends BaseCloth{ //裁剪
public function __construct(BaseCloth $cloth){
$this->cloth=$cloth;
$this->cloth();
}
public function cloth(){
return $this->cloth->cloth()." --->根据需求裁剪";
}
}
//布料加工。
$con=new CutCloth(new DyeingCloth(new BaseCloth("白布")));
echo $con->cloth();
?>