场景:要写一个订单系统,买了东西后要给用户发送email,改变订单状态,等等。
通常是这么写的:
class Order{
public function buy(){
echo ‘buy!‘;
$email = new Email();
$email -> doing();
$os = new orderStatus();
$os -> doing();
}
}
class Email{
public function doing(){
echo "send Email!!";
}
}
class orderStatus{
public function doing(){
echo "order finish!!";
}
}
$order = new Order();
$order -> buy();
这样就完成了?学了设计模式原则以后,怎么感觉坏极了。扩展性太差。order和email,orderstatus间的耦合太高了,类的复用性太差。(违反了开闭原则和迪米特法则)
class Order{
protect $observers = array();
public function addObserve($type, $observer){
$this -> observers[$type][] = $observer;
}
public function observer( $type ){
if(isset($this -> observers[$type])){
foreach($this -> observers[$type] as $observer){
$observer -> doing( $this );
}
}
}
public function buy(){
echo "buy!!!";
$this -> observer(‘buy‘);
}
}
interface IDo{
public function doing();
}
class Email implements IDo{
public function doing(){
echo "send Email!!";
}
}
class orderStatus implements IDo{
public function doing(){
echo "order finish!!";
}
}
$order = new Order();
$order -> addObserve(‘buy‘, new Email() );
$order -> addObserve(‘buy‘, new orderStatus () );
$order -> buy();
观察者模式:能够更便利创建和处理与核心对象相关对象的动作,并且提供和核心对象(order)非耦合的系列功能。
观察者模式非常实用,在这种场景下的应用能够最大程度的降低类之间的耦合度,提高类的复用性。
原文:http://my.oschina.net/shyl/blog/531674