2011-09-07 53 views
0

我在其中一個項目中實施了狀態模式,並且遇到了設計問題;可以抽象地描述了我的問題如下:狀態/策略模式 - 可見性問題

比方說,我有StatefulObject類,具有保持在currentState對象的狀態屬性。

大部分的功能,我想將currentState對象的訪問,被封裝在StatefulObject對象。

的問題是,允許訪問該功能迫使我提供,我本來也沒有暴露StatefulObject類的公共方法,並且也覺得我不應該。

我希望能就如何處理這一問題的可見性的建議。

執行語言是PHP,如果是的話。

我已經把一些示例代碼,可根據要求:

Class StatefulObject{ 

    protected $state; 

    public function StatefulObject(){ 
     $this->state = new PrepareSate($this); 
    } 

    public function execute(){ 
     $this->state->execute(); 
    } 

    /* I am not intrested in providing public access to these methods 
    Optimaly I would have this visible only for the PrepareState*/ 
    public function setX(){ 

    }; 
    public function setY(){ 

    }; 
} 

Abstract class StateObject{ 
    protected $stateFulObjectRef; 

    public function StateObject(StateFulObject $ref){ 
     $this->stateFulObjectRef = $ref; 
    } 
} 

Class PrepareState extends StateObject{ 
    public function execute(){ 
     /* This is why I need the public access for */ 
     $this->stateFulObjectRef->setX(); 
     $this->stateFulObjectRef->setY(); 
    } 
} 

我認爲,在Java中的解決方案將是具有與沒有訪問修飾符,這意味着它們將在可見的方法setX的塞蒂包級別。

雖然我不認爲PHP有​​同等的解決方案。

編輯,上可能的答案:

我想我想出了迄今爲止正在StatefulObject和StateObject的最佳解決方案繼承相同的父(僅用於可見性)。並聲明setX setY方法爲protected。兄弟姐妹班可以訪問PHP中的其他受保護方法 - 正如這裏指出的那樣 - http://www.php.net/manual/en/language.oop5.visibility.php#93743

+0

你的問題太抽象了,請提供一些源代碼 –

+0

我已經添加了一些示例代碼。 –

回答

0

這個問題非常籠統,但我會盡量根據我對您問題的理解(這可能不是正確理解問題)

我會建議你製作一個接口並在你的類中實現它,而不是使用該接口對象與這些方法進行交互。

+0

我不明白你的解決方案 –

0

如果您StateObject不需要訪問StatefulObject的話,那麼只是簡單的傳遞參數所需的值(策略模式)。

Class StatefulObject{ 

    protected $state; 

    public function StatefulObject(){ 
     $this->state = new PrepareSate($this); 
    } 

    public function execute(){ 
     $this->state->execute($this->x, $this->y); 
    } 

} 

Class PrepareState extends StateObject{ 
    public function execute($x, $y){ 
     // Now you have access to $x and $y. 
    } 
}