0

デコレータや状態パターンに最適だと思う問題を解決している最中です。高レベルの設定は、サンドイッチメーカーやディスペンサーのようなもので、一定量の材料といくつかの異なる種類のサドニッチを作ることができます。各成分には、それに関連するコストがあります。クライアントは、特定のスイッチを作るために材料を選択するために機械を使用する誰かであり、機械はそれを分配します。

これまで、デコレータパターンを使用して材料とさまざまな種類のサンドイッチを作成しました。

public abstract class Sandwich {
    String description = "Unknown Sandwich";

    public String getDescription(){
        return description;
    }

    public double cost(){
        return 0.0;
    }
}

各成分はこれでモデル化されています:

public abstract class Ingredient extends Sandwich {
    public abstract String getDescription();
}

さらに、具体的な成分は次のようになります。

public class Cheese extends Ingredient {
    private Sandwich sandwich;

    public Cheese(Sandwich sandwich){
        this.sandwich = sandwich;
    }

    public String getDescription() {
        return sandwich.getDescription() + ", cheese";
    }

    public double cost() {
        return 0.25 + sandwich.cost();
    }
}

特定の種類のサンドイッチは、次のようにモデル化できます。

public class BLT extends Sandwich {
    public BLT(){
        description = "Bacon, Lettuce and Tomato";
    }
}

したがって、クライアントは次のような特定のサンドイッチを作成します。

Sandwich order_a_blt = new Tomato(new Lettuce(new Bacon(new Bread(new BLT()))));

次のステップとして、自動マシンとして機能するディスペンサーオブジェクトを作成します。このオブジェクトには、特定の数の材料(一般的な単位で測定)が事前にロードされており、ユーザーはボタンを押して事前のいずれかを選択できます。 -選択を設定します:

例えば

  • BLT:トマト1単位、レタス1単位、ベーコン1単位、パン1単位
  • SUB:1ユニットのミートボール、1ユニットのチーズ、1ユニットのitalian_sauce、1ユニットのパン
  • 等..

私のディスペンサーマシンには、材料ごとに固定数のユニットがプリロードされています

  • トマト:10
  • レタス:10
  • ベーコン:10
  • 等..

また、ユーザーが特定の種類のサンドイッチを選択するためのボタンのリスト:

  • 1-BLT
  • 2-SUB
  • 3-バーベキュー
  • ..等

材料の内部容量を追跡し、たとえば、別のBLTを作成するのに十分なベーコンが残っていないことをユーザーに伝えることができるようにするという考え方です。

さて、私の最初の考えは、状態デザインパターンに基づいてDispenserオブジェクトを作成することですが、IngredientクラスのオブジェクトをDispenserクラス内のある種のストレージと組み合わせようとして問題が発生しました。最初は、名前/値のマップが成分タイプ/成分量のペアになっています。しかし、使用するたびに自動的にデクリメントできるように、これらのパターンを組み合わせる方法がわかりません。

そのような概念をどのように進めて実装するかについて、一般的な考えはありますか?まず第一に、私はデコレータと状態パターンで正しい軌道に乗っていますか?より効率的なアプローチはありますか?問題を明確に説明できたと思います。

どんな方向性もありがとう、私はどんな考えにも感謝します

4

3 に答える 3

3

Sandwich to Cheeseは「has-a」関係であるため、SandwichがCheeseの親になることはありません。

この行で何をしているのかわからない:

Sandwich order_a_blt = new Tomato(new Lettuce(new Bacon(new Bread(new BLT()))));

論理的に言えば、なぜトマトオブジェクトを作成してレタスを渡すのですか?トマト、レタス....などは材料を拡張する必要があります。

こんな感じにします

class Sandwich{ public Sandwich(Ingredients ...ing){}}

各材料クラス内に、Tomatoに静的変数を配置し、それをtomatoCountと呼び、ディスペンサーを作成するときに初期化します。新しいTomatoが作成されるたびに、それがデクリメントされます。それがゼロに達すると、トマトクラスは文句を言うでしょう

于 2009-11-13T03:53:59.990 に答える
2
  1. 材料はIS-Aサンドイッチではありません。
  2. 柔軟な変更を可能にするために、原材料の価格を外部化することをお勧めします。
  3. クラスレベルでハードコーディングするのではなく、その成分に基づいて実行時にサンドイッチの説明を生成することをお勧めします。
  4. 材料はサンドイッチについて何も知らないはずです。

だから、私は次の解決策を提供します:

package com;

public enum Ingredient {

 CHEESE, TOMATO, LETTUCE, BACON, BREAD, MEATBALL, ITALIAN_SAUCE;

 private final String description;

 Ingredient() {
  description = toString().toLowerCase();
 }

 Ingredient(String description) {
  this.description = description;
 }

 public String getDescription() {
  return description;
 }
}


package com;

import static com.Ingredient.*;

import java.util.*;
import static java.util.Arrays.asList;

public enum SandwitchType {

 BLT(
   asList(TOMATO, LETTUCE, BACON, BREAD),
             1  ,    1,      1  ,   1
 ),
 SUB(
   asList(MEATBALL, CHEESE, ITALIAN_SAUCE, BREAD),
              1   ,    1  ,      1       ,   1
 );

 private final Map<Ingredient, Integer> ingredients = new EnumMap<Ingredient, Integer>(Ingredient.class);
 private final Map<Ingredient, Integer> ingredientsView = Collections.unmodifiableMap(ingredients);

 SandwitchType(Collection<Ingredient> ingredients, int ... unitsNumber) {
  int i = -1;
  for (Ingredient ingredient : ingredients) {
   if (++i >= unitsNumber.length) {
    throw new IllegalArgumentException(String.format("Can't create sandwitch %s. Reason: given ingedients "
      + "and their units number are inconsistent (%d ingredients, %d units number)", 
      this, ingredients.size(), unitsNumber.length));
   }
   this.ingredients.put(ingredient, unitsNumber[i]);
  }
 }

 public Map<Ingredient, Integer> getIngredients() {
  return ingredientsView;
 }

 public String getDescription() {
  StringBuilder result = new StringBuilder();
  for (Ingredient ingredient : ingredients.keySet()) {
   result.append(ingredient.getDescription()).append(", ");
  }

  if (result.length() > 1) {
   result.setLength(result.length() - 2);
  }
  return result.toString();
 }
}


package com;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class PriceList {

 private static final int PRECISION = 2;

 private final ConcurrentMap<Ingredient, Double> prices = new ConcurrentHashMap<Ingredient, Double>();

 public double getPrice(SandwitchType sandwitchType) {
  double result = 0;
  for (Map.Entry<Ingredient, Integer> entry : sandwitchType.getIngredients().entrySet()) {
   Double price = prices.get(entry.getKey());
   if (price == null) {
    throw new IllegalStateException(String.format("Can't calculate price for sandwitch type %s. Reason: "
      + "no price is defined for ingredient %s. Registered ingredient prices: %s",
      sandwitchType, entry.getKey(), prices));
   }
   result += price * entry.getValue();
  }
  return round(result);
 }

 public void setIngredientPrice(Ingredient ingredient, double price) {
  prices.put(ingredient, round(price));
 }

 private static double round(double d) {
  double multiplier = Math.pow(10, PRECISION);
  return Math.floor(d * multiplier + 0.5) / multiplier;
 }
}


package com;

import java.util.Map;
import java.util.EnumMap;

public class Dispenser {

 private final Map<Ingredient, Integer> availableIngredients = new EnumMap<Ingredient, Integer>(Ingredient.class);

 public String buySandwitch(SandwitchType sandwitchType) {
  StringBuilder result = new StringBuilder();
  synchronized (availableIngredients) {

   Map<Ingredient, Integer> buffer = new EnumMap<Ingredient, Integer>(availableIngredients);
   for (Map.Entry<Ingredient, Integer> entry : sandwitchType.getIngredients().entrySet()) {
    Integer currentNumber = buffer.get(entry.getKey());
    if (currentNumber == null || currentNumber < entry.getValue()) {
     result.append(String.format("not enough %s (required %d, available %d), ",
       entry.getKey().getDescription(), entry.getValue(), currentNumber == null ? 0 : currentNumber));
     continue;
    }
    buffer.put(entry.getKey(), currentNumber - entry.getValue());
   }

   if (result.length() <= 0) {
    availableIngredients.clear();
    availableIngredients.putAll(buffer);
    return "";
   }
  }
  if (result.length() > 1) {
   result.setLength(result.length() - 2);
  }
  return result.toString();
 }

 public void load(Ingredient ingredient, int unitsNumber) {
  synchronized (availableIngredients) {
   Integer currentNumber = availableIngredients.get(ingredient);
   if (currentNumber == null) {
    availableIngredients.put(ingredient, unitsNumber);
    return;
   }
   availableIngredients.put(ingredient, currentNumber + unitsNumber);
  }
 }
}


package com;

public class StartClass {
 public static void main(String[] args) {
  Dispenser dispenser = new Dispenser();
  for (Ingredient ingredient : Ingredient.values()) {
   dispenser.load(ingredient, 10);
  }
  PriceList priceList = loadPrices();
  while (true) {
   for (SandwitchType sandwitchType : SandwitchType.values()) {
    System.out.printf("About to buy %s sandwitch. Price is %f...",
      sandwitchType, priceList.getPrice(sandwitchType));
    String rejectReason = dispenser.buySandwitch(sandwitchType);
    if (!rejectReason.isEmpty()) {
     System.out.println(" Failed: " + rejectReason);
     return;
    }
    System.out.println(" Done");
   }
  }
 }

 private static PriceList loadPrices() {
  PriceList priceList = new PriceList();
  double i = 0.1;
  for (Ingredient ingredient : Ingredient.values()) {
   priceList.setIngredientPrice(ingredient, i);
   i *= 2;
  }
  return priceList;
 }
}
于 2009-11-13T08:49:03.747 に答える
1

デコレータパターンは問題に適していません。Ingredientは、サンドイッチに新しい動作を追加しません。サンドイッチと(サンドイッチ)Ingredientをis-a関係でリンクすることは、すでに少し工夫されていることを気にしないでください。(ネストされたインスタンス化は、動的に実行する必要があるまではクールに見えます。)

サンドイッチには材料/詰め物/調味料があります。材料のクラス階層を確立し、複合パターンを使用してサンドイッチと一緒に折ります。

public abstract class Ingredient {
    protected Ingredient(Object name) { ... }
    public String name() { ... }
    public abstract String description();
    public abstract double cost();
}

public Cheese extends Ingredient {
    public Cheese() { super("Cheese"); }
    public String description() { ... }
    public double cost() { return 0.25; }
|

public abstract class Sandwich {
   public abstract double cost();
   public Set<Ingredient> fillings() { ... }
   public boolean addFilling(Ingredient filling) { ... }
   public boolean removeFilling(Ingredient filling) { ... }
   public double totalFillingsCost();
   ...
}

public class SubmarineSandwich extends Sandwich {
   public SubmarineSandwich() { ... }
   public double cost() { return 2.50 + totalFillingsCost(); }   
}

public enum SandwichType { 
    Custom,
    Blt,
    Sub,
    ...
}

public class SandwichFactory  {
    public Sandwich createSandwich(SandwichType type) {
        switch (type) {
            case Custom:
                return new Sandwich() { public double cost() { return 1.25; } };
            case Blt:
                return new BaconLettuceTomatoSandwich();
            case Sub:
               return new SubmarineSandwich();
            ....
        }
    }
}

あまりにも、州のパターンは材料やサンドイッチの管理に関連しているため、ディスペンサーには役立たないと思います。このパターンは、クラスの動作を変更するためのオブジェクトの内部使用を規定しています。ただし、DIspenserは、状態に基づくポリモーフィックな動作を必要としません。

public class SandwichDispenser {
    ...
    public void prepareSandwich(SandwichType type) throws SupplyException { ... }
    public Sandwich finalizeSandwich() throws NotMakingASandwichException { ... }
    public boolean addFilling(Ingredient filling) throws SupplyException { ... } 
}

たとえば、ディスペンサーには、パブリックインターフェイスのポリモーフィックな動作を必要とする内部状態に大きな変動はありません。

于 2009-11-13T06:23:51.450 に答える