2010-12-20 144 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