0

I have a simple Store class that contains an Inventory object and a CashRegister object. In order to sell an item, the CashRegister object needs to access the Inventory object's methods; namely, those which return a particular item's price, quantity held in storage, etc. What's the best way to give the CashRegister object access to the Inventory object's methods?

Thank you.

4

4 に答える 4

3

Inventory1 つの解決策は、オブジェクトへの参照をオブジェクトに格納し、オブジェクトCashRegisterの構築時に参照を与えることStoreです。

class Inventory { /* ... */ };

class CashRegister
{
public:
    CashRegister(Inventory &inventory)
        : inventory_(inventory)
    { }

    // ....

private:
    Inventory &inventory_;
};

class Store
{
public:
    Store()
        : cashregister_(inventory_)
    { }

    // ....

private:
    Inventory inventory_;
    CashRegister cashregister_;
};
于 2012-05-24T09:20:11.150 に答える
3

CashRegister オブジェクトは Inventory オブジェクトのメソッドにアクセスする必要があります

なんで?はCashRegisterがなくても完全に存在し、動作することができますInventoryCashRegisterだけでなく、劇場や映画館でを持つことができますStore。あなたが話しているロジックのこの部分は、ストアの一部である必要があります。

class Store
{
   CashRegister register;
   Inventory I;
   void sellSomething(Item i)
   {
      //move logic inside the store
      //not in CashRegister
      int price = I.getPrice(i);
      register.addCash(price);
      I.removeItem(i);
   }
};
于 2012-05-24T09:18:31.903 に答える
1

オブジェクトに責任を与え、データをまとめるだけに使用しないでください。

Inventory、 を追加および削除する方法を知っている必要がありますItem。トランザクションが発生する必要がある場合があります。この割り当ては、データベースのメタファーです。

@Luchianは正しい考えを持っていますが、私はそれをさらに進めます。

Inventory(データベース)が s を処理できるようにする必要があります。Transactionこの場合は、キャッシュ レジスタの使用に特化したものです。

Item、 に対して自身を表すことができる必要がありInventoryます。

Tell Don't AskWrite No Gettersのアイデアを見てください。

于 2012-05-24T09:34:29.163 に答える
1
class Inventory {
  Currency price;
  uint64_t quantity;
  public:
    Currency get_price() { return price; }
    uint64_t get_quantity() { return quantity; }
};

その後、キャッシュ レジスタは のインスタンスで関数を呼び出すことができますInventory

しかし、実際には、Inventory利用可能な場合に特定の数のオブジェクトを予約または配達する関数を配置する必要があります。キャッシュ レジスタは、在庫にあるアイテムの数を知る必要はなく、現在の需要を満たすことができるかどうかを知るだけで済みます。さらに言えば、オブジェクトの価格を知る必要があるかどうかもわかりません。Inventory水曜日の午後に 10% オフの場合、倉庫の業務は何ですか?

于 2012-05-24T09:19:20.563 に答える