2010-12-20 146 views
1

我有一个类人,我想使用Strategy模式来添加存储行为。这样策略模式问题 - PHP

interface Storage{ 
public function store(); 
} 

class LocalStorage implements Storage(){ 
public function store(){ 
.. 
// save in a file 
.. 
} 
} 

class Person{ 
    private $behaviourStorage; 
    private $name; 
    private $age; 

    public function __construct(Storage $objStorage,$name,$age) { 
    $this->behaviourStorage = $objStorage; 
    } 
    public function Store(){ 
    $this->behaviourStorage->store(); 
    } 

    } 

    $objPerson = new Person(new LocalStorage(),'John',32); 

我的问题有什么东西,我怎么能使用存储性保存对象的人的信息?如何将对象传递给LocalStorage,以便知道要保存的内容?

也许这毕竟不是正确的设计模式,但意图很明确:为人物实现不同的存储行为。

回答

3

要么修改Person::Store(),以便它调用$this->behaviourStorage->store($this),然后检查传递给该方法的对象中的字段,或者让它调用$this->behaviourStorage->store()并存储字段值。

+0

这是完美的:$ this-> behaviourStorage-> store($ this)。战略模式在这种情况下是否正确应用?谢谢 – danidacar 2010-12-20 06:38:19

+1

如果'Storage'可以存储在需要存储的字段中。 – 2010-12-20 06:39:38