我在其中一個項目中實施了狀態模式,並且遇到了設計問題;可以抽象地描述了我的問題如下:狀態/策略模式 - 可見性問題
比方說,我有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
你的問題太抽象了,請提供一些源代碼 –
我已經添加了一些示例代碼。 –