在java中结合装饰器和状态模式 - 关于OO设计的问题

时间:2009-11-13 03:33:59

标签: java design-patterns oop decorator state

我正在解决一个问题,我认为它最适合装饰器和状态模式。高级设置就像一个三明治制造商和分配器,我有一定数量的成分和一些不同类型的sadnwiches我可以做。每个ingedient都有与之相关的成本。客户可能会使用机器选择配料来制作特定的swndwich,机器会分配它。

到目前为止,我已经使用装饰器模式创建了成分和不同类型的三明治:

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()))));

作为下一步,我将创建一个Dispenser对象,它将作为一个自动机器,预先加载特定数量的成分(以通用单位测量),用户可以按一个按钮选择一个预先设定的选择:

例如

  • BLT:1单位番茄,1单位 生菜,1单位培根,1单位面包
  • SUB:1个单位肉丸,1个单位奶酪, 1单位italian_sauce,1单位面包
  • 等。

我的分配器机器预装了每种成分固定数量的单位

  • 番茄:10
  • 生菜:10
  • 培根:10
  • 等。

用户可以选择特定三明治的按钮列表:

  • 1-BLT
  • 2-SUB
  • 3- BBQ
  • ..等

这个想法是跟踪成分的内部容量,并告诉用户,比方说,我们没有足够的培根来制作另一个BLT

现在,我最初的想法是根据状态设计模式创建Dispenser对象,但是我试图将Ingredient类的对象与Dispenser类中的某种存储结合起来遇到了问题。起初我虽然名称/值的地图配对成分类型/成分数量。但我不确定如何将这些模式组合在一起,所以我可以在每次使用后自动减量。

您是否对如何继续实施这样的概念有一个大概的想法?首先,我是否在装饰和状态模式的正确轨道上?会有更有效的方法吗?我希望我已经清楚地解释了这个问题。

感谢您的任何指导,我感谢任何想法

3 个答案:

答案 0 :(得分:3)

三明治到奶酪是“有一种”关系,所以三明治不应该是奶酪的父母。

不确定你在这一行做了什么:

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

从逻辑上讲,为什么要创建一个Tomato对象并将其传递给Lettuce? 番茄,生菜等应该扩展成分。

我会这样做

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

在每个成分类中,我会在Tomato中放置一个静态变量,将其称为tomatoCount,然后在创建Dispenser时初始化它,每次创建一个新的Tomato会减少它。如果它达到零,则番茄类会抱怨

答案 1 :(得分:2)

  1. 成分不是IS-A三明治;
  2. 最好将原料价格外部化,以便灵活变换;
  3. 最好生成三明治 基于它的运行时描述 成分而不是硬编码 在班级;
  4. 成分应该一无所知 关于三明治;
  5. 所以,我会提供以下解决方案:

    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;
     }
    }
    

答案 2 :(得分:1)

装饰器模式不适合您的问题。成分不会在三明治中添加新的行为,更不用说将三明治和(三明治)成分链接在 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 { ... } 
}
例如,分配器内部状态没有明显的差异,因此需要对其公共接口进行多态行为。