抽象工厂模式是创造型模式的一种,他和工厂模式类似,可以看作是工厂的工厂
工厂模式中使用一堆 if-else结构来返回客户端要的子类实例。抽象工厂模式不是用if-else,而是使用不同子类的工厂代理来返回子类实例
下面例子对之前工厂模式进行适当的修改,增加生成PC的PCFactory, 生成Server的ServerFactory ,以及修改ComputerFactory
PCFactory.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.walterlife.dp.FactoryDP;public class PCFactory implements ComputerAbstractFactory { private String ram; private String hdd; private String cpu; public PCFactory (String ram, String hdd, String cpu) { this .ram = ram; this .hdd = hdd; this .cpu = cpu; } @Override public Computer createComputer () { return new PC(ram, hdd, cpu); } }
ServerFactory.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package com.walterlife.dp.FactoryDP;public class ServerFactory implements ComputerAbstractFactory { private String ram; private String hdd; private String cpu; public ServerFactory (String ram, String hdd, String cpu) { this .ram = ram; this .hdd = hdd; this .cpu = cpu; } @Override public Computer createComputer () { return new Server(ram, hdd, cpu); } }