1 基本介绍
抽象工厂模式:定义一个接口用于创建相关或有依赖关系的对象簇,而无需指明具体的类。
抽象工厂模式可以将简单工厂模式和工厂方法模式进行整合
简单工厂模式和工厂方法模式以及下面用到的一些类参考:23种设计模式2_工厂模式。
2 代码演示
interface SellType {
public void sellFruit();
}
// 直接售卖
public class Sell implements SellType {
public void sellFruit() { System.out.println("直接售卖水果"); }
}
// 做成水果捞进行售卖
public class SellMix implements SellType {
public void sellFruit() { System.out.println("做成水果捞进行售卖"); }
}
// 做成水果果盘进行售卖
public class SellCompote implements SellType {
public void sellFruit() { System.out.println("做成水果果盘进行售卖"); }
}
// 做成果汁进行售卖
public class SellJuice implements SellType {
public void sellFruit() { System.out.println("做成果汁进行售卖"); }
}
public class FruitOrder {
private SimpleFruitFactory fruitFactory = new SimpleFruitFactory();
public void addFruit(String fruitType, SellType sellType) {
Fruit fruit = fruitFactory.makeFruit(fruitType);
if (fruit == null) {
System.out.println("该水果卖完了。。。");
return;
}
sellType.sellFruit();
}
}
public class FruitStore {
public static void main(String[] args) {
FruitOrder fo = new SellJuice();
fo.addFruit("mango", new SellJuice());
fo.addFruit("watermelon", new SellMix());
}
}