快捷搜索:  as  2018  FtCWSyGV  С˵  test  xxx  Ψһ  w3viyKQx

和记APP:PHP设计模式实例之(观察者模式、策略模式、简单工厂模式)



察看者模式

/**

* 定义察看接口

*/

interface Subject

{

public function Attach($Observer); //添加察看者

public function Detach ($Observer); //踢出察看者

public function Notify(); //满意前提时看护察看者

public function SubjectState($Subject); //察看前提

}

/**

* 察看类的详细实 现

*/

class Boss Implements Subject

{

public $_action;

private $_Observer;

public function Attach($Observer)

{

$this->_Observer[] = $Observer;

}

public function Detach ($Observer)

{

$ObserverKey = array_search($Observer, $this- >_Observer);

if($ObserverKey !== false)

{

unset($this->_Observer[$ObserverKey]);

}

}

public function Notify()

{

foreach($this->_Observer as $value )

{

$value->Update();

}

}

public function SubjectState($Subject)

{

$this->_action = $Subject;

}

}

/**

* 抽象察看者

*

*/

abstract class Observer

{

protected $_UserName;

protected $_Sub;

public function __construct($Name,$Sub)

{

$this->_UserName = 和记APP$Name;

$this->_Sub = $Sub;

}

public abstract function Update(); //接管经由过程措施

}

/**

* 察看者

*/

class StockObserver extends Observer

{

public function __construct($name,$sub)

{

parent::__construct($name,$sub);

}

public function Update()

{

echo $this->_Sub->_action.$this->_UserName." 你从速 跑...";

}

}

$huhansan = new Boss(); //被察看者

$gongshil = new StockObserver("三毛",$huhansan); //初始化察看者

$huhansan->Attach ($gongshil); //添加一个察看者

$huhansan->Attach($gongshil); //添加一个相同的察看者

$huhansan->Detach($gongshil); //踢出基中一个察看者

$huhansan- >SubjectState("警察来了"); //达到满意的前提

$huhansan->Notify(); //通 过所有有效的察看者

策略模式

/**

* 定义支持算法的接口

*

*/

abstract class Strategy

{

abstract public function和记APP AlgorithmInterface();

}

class ConcreateStratA extends Strategy

{

public function AlgorithmInterface()

{

echo "算法A";

}

}

class ConcreateStratB extends Strategy

{

public function AlgorithmInterface()

{

echo "算法B";

}

}

class ConcreateStratC extends Strategy

{

public function AlgorithmInterface()

{

e和记APPcho "算法C";

}

}

class Context

{

private $_StrObj;

public function __construct($strobj)

{

$this->_StrObj = $strobj;

}

public function ContextInterface()

{

$this->_StrObj- >AlgorithmInterface();

}

}

$context =和记APP new Context(new ConcreateStratA);

$context->ContextInterface();

$context = new Context(new ConcreateStratC);

$context->ContextInterface();

$context = new 和记APPContext(new ConcreateStratB);

$context->ContextInterface();

您可能还会对下面的文章感兴趣: