1. 程式人生 > >委托模式/中介者模式/策略模式

委托模式/中介者模式/策略模式

ets name delegate end 動態創建 list 相同 工廠模式 col

委托模式

通過分配或委托到其他對象,去除核心對象中的判決或復雜功能,動態添加新功能.

class A
{
    public function song($songList)
    {
        foreach($songList as $val) {
            echo $val . ‘.mp3‘;
        }
    }
}

class B
{
    public function song($songList)
    {
        foreach($songList as $val) {
            echo $val . ‘.wav‘;
        }
    }
}

class Delegate
{
    private $obj;
    private $songList = array();
    public function __construct()
    {
    }

    public function setDelegate($type)
    {
        $this->obj = new $type();
    }

    public function addSong($name)
    {
        $this->songList[] = $name;
    }

    public function song()
    {
        $this->obj->song($this->songList);
    }
}

// 調用
$delegate = new Delegate();
$delegate->setDelegate(‘A‘);
$delegate->addSong(‘rolling in the deep‘);
$delegate->song();

  

 

特點:
每個委托的對象都擁有一個相同的public方法名.
動態創建委托對象.
委托模式下,委托對象是依據被委托者Delegate中不同的數據類型,來對數據做處理.數據還是Delegate中的,只有這樣子,才能叫委托.這也是他區別工廠模式的一個重要特點.

  

策略模式

構建的對象不必自身包含邏輯,而是根據需要利用其它對象中的算法.

我們為類的輸出數據,同時提供json和xml格式,至於使用那麽格式由外部調用者決定.

class User
{
    private $uid, $name;
    protected $strategy;

    public function __construct($uid, $name)
    {
        $this->uid = $uid;
        $this->name = $name;
    }

    public function getUid()
    {
        return $this->uid;
    }

    public function getName()
    {
        return $this->name;
    }

    // 設置策略
    public function setStrategy($obj)
    {
        $this->strategy = $obj;
    }

    public function get()
    {
        return $this->strategy->get($this);
    }

}

class JsonStrategy
{
    public function get(User $user)
    {
        return json_encode(array(‘uid‘ => $user->getUid(), ‘name‘ => $user->getName()));
    }
}

class XmlStrategy
{
    public function get(User $user)
    {
        $doc = new DOMDocument();
        $root = $doc->createElement(‘user‘);
        $root = $doc->appendChild($root);

        $elementUid = $doc->createElement(‘uid‘, $user->getUid());
        $root->appendChild($elementUid);

        $elementName = $doc->createElement(‘name‘, $user->getName());
        $root->appendChild($elementName);

        return $doc->saveXML();
    }
}

$user = new User(‘1‘, ‘jack‘);
$user->setStrategy(new XmlStrategy());
echo $user->get();

$user->setStrategy(new JsonStrategy());
echo $user->get();

  

委托模式/中介者模式/策略模式