0

キーボード、Tシャツ、コーラのボトルの3つのアイテムがあるとしましょう。

$keyboard = new Item("Keyboard");
echo $keyboard->getPrice(); // return 50;

$tshirt = new Item("Tshirt");
echo $tshirt->getPrice(); // return 20;

$cola = new Item("Cola");
echo $cola->getPrice(); // return 0 or 2 whether the bottle is empty or not.

Priceコーラのボトルを入手するためのベストプラクティスは何ですか?

私は2つのクラスを作成することから始めました:

Class Item {
    $this->price;

    function __construct($name) {
    // ...
    }

    public function getPrice() {
        return $this->price;
    }
}

Class Bottle extends Item {
    $this->empty;

    function __construct($name) {
    // get from database the value of $this->empty
    }
    public function getPrice() {
        if($this->empty)
            return 0;
        else 
            return $this->price;
    }
}

しかし今、私は疑問に思っています; :を使用すると、オブジェクトではなくオブジェクトを$cola = new Item("Cola");インスタンス化しています。これは、それが「通常の」アイテムなのかボトルなのかまだわからないためです。ItemBottle

代わりに、Bottleオブジェクトをインスタンス化して、アプリケーション内の別のロジックを調査する必要がありますか?または、アイテムオブジェクトを「再作成」して、ボトルとして変換する方法はありますか?

4

1 に答える 1

2

これは、ファクトリパターンを使用する場合の完璧な例です。

あなたのコードのために、あなたはこのようなことをすることができます。

class ItemFactory {
    // we don't need a constructor since we'll probably never have a need
    // to instantiate it.
    static function getItem($item){
        if ($item == "Coke") {
            return new Bottle($item);
        } else if ( /* some more of your items here */){
            /*code to return object extending item*/
        } else { 
            // We don't have a definition for it, so just return a generic item.
            return new Item($item);
        }
    }
}

あなたはそれを次のように使うことができます$item = ItemFactory::getItem($yourvar)

ファクトリパターンは、同じ基本(または親)クラスを持つオブジェクトが多数あり、実行時にそれらがどのクラスであるかを判別する必要がある場合に役立ちます。

于 2012-04-30T03:43:33.903 に答える