我正在閱讀有關可用的不同模式。目前我在抽象工廠模式,我認爲我對它有很好的把握。我的資源,除了維基百科: http://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm http://www.oodesign.com/abstract-factory-pattern.html https://github.com/domnikl/DesignPatternsPHP/tree/master/Creational/AbstractFactoryPHP抽象工廠模式實現
我使用蘋果公司和它的產品做一個樣品Abstract Factory模式的一個例子。我明白代碼重複是不好的設計,因此我寫這個的原因。我的代碼到目前爲止是:
abstract class AbstractAppleFactory {
abstract public function createiPod($capacity, $type, $color, $engraving);
abstract public function createiPhone($capacity, $type, $color, $antenna);
abstract public function createComputer($type, $HDCapacity, $CPU, $ram);
}
class iPodFactory extends AbstractAppleFactory {
public function createiPod($capacity, $type, $color, $engraving) {
$class = 'iPod' . $type;
return new $class($capacity, $color, $engraving);
}
public function createiPhone($capacity, $type, $color, $antenna){ /* no implementation necessary */}
public function createComputer($type, $HDCapacity, $CPU, $ram){ /* no implementation necessary */}
}
interface iPlayer {
public function play();
public function stop();
public function fastForward();
public function rewind();
}
abstract class iPod implements iPlayer {
protected $capacity;
protected $color;
protected $engraving;
public function __construct($capacity, $color, $engraving = null) {
$this->capacity = $capacity;
$this->color = $color;
$this->engraving = $engraving;
}
}
class iPodClassic extends iPod {
public function play() {/* implementation goes here */}
public function stop() {/* implementation goes here */}
public function fastForward() {/* implementation goes here */}
public function rewind() {/* implementation goes here */}
}
class iPodShuffle extends iPod {
public function play() {/* implementation goes here */}
public function stop() {/* implementation goes here */}
public function fastForward() {/* implementation goes here */}
public function rewind() {/* implementation goes here */}
}
等等。有太多的代碼放在這裏。我知道在目錄和命名空間中組織更好。這不是我現在正在學習的東西。我正在學習模式和麪向對象的概念。
有問題的部分是:
class iPodFactory extends AbstractAppleFactory {
public function createiPod($capacity, $type, $color, $engraving) {
$class = 'iPod' . $type;
return new $class($capacity, $color, $engraving);
}
public function createiPhone($capacity, $type, $color, $antenna){ /* no implementation necessary */}
public function createComputer($type, $HDCapacity, $CPU, $ram){ /* no implementation necessary */}
}
由於繼承/抽象我被迫實施無關二廠不必要的方法。 createiPhone()
和createComputer()
。我在做抽象工廠模式嗎?再次,「代碼重複是糟糕的設計!」還有什麼更好的辦法呢?
您是否必須堅持整個項目的一種模式?我個人根據需要使用設計模式。你有沒有考慮過使用依賴注入來將你的iPhone對象注入到任何類中,這樣你就可以使用它的方法了? – Joao
這只是一個練習。 –