和工厂方法 类似;只是 每一个具体的工厂可以 创建多种“产品”
优缺点 优点对调用者更友好:调用者无需了解"产品"的创建细节,直接调用工厂创建即可;如果随着业务修改,新增"产品",无需修改原工厂,只需要新增具体工厂类即可;符合“开闭原则” 缺点
如果工厂中新增一个"产品"组成,修改修改 此抽象工厂的 所有具体实现 适用场景
调用者不关心 “产品” 具体的创建细节;只想要 由多种"产品"组成的结果 主要组成结构
抽象工厂:生产 “产品” 的 共性抽象具体工厂:包含具体的 生产 “产品” 的工厂实现抽象产品:"产品"种类的共性抽象,产品类型定义具体产品:具体的产品实现 类图
代码实现public class AbstractFactoryPattern { public static void main(String[] args) { final SetMeal chicken1SetFactory = new Chicken1SetFactory(); chicken1SetFactory.create(); System.out.println(chicken1SetFactory); final SetMeal chicken2SetFactory = new Chicken2SetFactory(); chicken2SetFactory.create(); System.out.println(chicken2SetFactory); } } interface Drink { Drink create(); } class Coffee implements Drink{ @Override public Drink create() { System.out.println("咖啡"); return new Coffee(); } } class Coke implements Drink{ @Override public Coke create() { System.out.println("可乐"); return new Coke(); } } interface StapleFood { StapleFood create(); } class Hamburger implements StapleFood{ @Override public StapleFood create() { System.out.println("汉堡"); return new Hamburger(); } } class ChickenRolls implements StapleFood{ @Override public StapleFood create() { System.out.println("鸡肉卷"); return new ChickenRolls(); } } interface Snack { Snack create(); } class ChickenNuggets implements Snack{ @Override public Snack create() { System.out.println("鸡块"); return new ChickenNuggets(); } } class PopcornChicken implements Snack{ @Override public Snack create() { System.out.println("鸡米花"); return new PopcornChicken(); } } interface SetMeal { void create(); } class Chicken1SetFactory implements SetMeal{ Drink drink; StapleFood stapleFood; Snack snack; @Override public void create() { final Coke coke = new Coke(); final Hamburger hamburger = new Hamburger(); final PopcornChicken popcornChicken = new PopcornChicken(); snack = popcornChicken.create(); stapleFood = hamburger.create(); drink = coke.create(); } @Override public String toString() { return "Chicken1SetFactory{" + "drink=" + drink + ", stapleFood=" + stapleFood + ", snack=" + snack + '}'; } } class Chicken2SetFactory implements SetMeal{ Drink drink; StapleFood stapleFood; Snack snack; @Override public void create() { final Drink coke = new Coke(); final StapleFood chickenRolls = new ChickenRolls(); final Snack popcornChicken = new PopcornChicken(); snack = popcornChicken.create(); stapleFood = chickenRolls.create(); drink = coke.create(); } @Override public String toString() { return "Chicken2SetFactory{" + "drink=" + drink + ", stapleFood=" + stapleFood + ", snack=" + snack + '}'; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)