设计模式之抽象工厂模式

来源:互联网 发布:js遍历object对象list 编辑:程序博客网 时间:2024/06/05 02:05

接上文 工厂方法模式

    很多读者读完工厂方法模式,认为这很不错,不过你能看出它明显的弊端吗,需求总是变换的,工厂方法模式,抽象工厂里面有个生产实例的方法。对于一种良好的模式,工厂方法模式中,一种产品应该对应一个抽象工厂,那么你新增一个电脑(computer),你就要新增一个抽象工厂,还要新增一个抽象工厂的的实现类,这很麻烦,关键在于你要新增很多东西,所以麻烦。

    我们可以在一个抽象工厂里面生产所有的抽象产品,比如computer,mobile,让继承抽象工厂的类去创建具体的产品,根据用户需要自己创建。



abstract class Cpu {    abstract String getName();}public class Intel extends Cpu{@OverrideString getName() {return "奔腾4 3.2C";}}public class AMD extends Cpu{@OverrideString getName() {// TODO Auto-generated method stubreturn "Athlon XP 2008+";}}abstract class HardDisk {    abstract String getSize();}public class WestDigit extends HardDisk{@OverrideString getSize() {// TODO Auto-generated method stubreturn "WD2500JD 250G";}}public class Maxtor extends HardDisk{@OverrideString getSize() {// TODO Auto-generated method stubreturn "MaXLine Plus II 200G";}}abstract class MainBoard {    abstract void attach(Cpu cpu) throws Exception;}public class MSI865PE extends MainBoard{@Overridevoid attach(Cpu cpu) throws Exception {if(cpu.getClass ().toString ().endsWith("Intel")){            System.out.println("MSI865PE");        }         else{            throw new Exception("主板MSI865PE只能配Intel的 CPU");        }}}public class MSIK7N2G extends MainBoard{@Overridevoid attach(Cpu cpu) throws Exception {if(cpu.getClass().toString().endsWith("Intel")){System.out.println("MSIK7N2G");}else{throw new Exception("主板MSIK7N2G只能配AMD的CPU");}}}public class Ibm extends ComputerFactory{    Ibm(){    cpu = new Intel();    hardDisk = new WestDigit();    mainBoard = new MSI865PE();    }}public class Dell extends ComputerFactory{    Dell(){    cpu = new AMD();    hardDisk = new Maxtor();    mainBoard = new MSIK7N2G();    }}public class Client {    public static void main(String[] args) throws Exception{    Ibm ibm = new Ibm();    ibm.show();    }}


自己体会这种设计的好处,比如,可以根据需要创建IBM或者Dell的工厂,每个工厂都能生产多种产品,无论你新加产品还是新加工厂,只需增加类即可,而且每个工厂都有不同的组合方式,真是太过瘾了。。。未完待续