标签:
具体的工厂对象负责生产具体的产品对象;
符合开放--封闭"原则(OCP),新增产品时,只需新增工厂的实现类、产品的实现类,不修改原来的代码;
属于23种GOF设计模式中的一种;
具体工厂‘继承‘抽象工厂;
具体产品‘继承‘抽象产品;
每个具体工厂负责生产对应的具体产品;
产品使用者使用每个具体工厂生产的具体产品;
【抽象工厂】定义一个工厂接口,包含一个创建实例的方法,如下:
package com.pichen.dp.creationalpattern.factorymethod; public interface IFatherFactory { public Father createFather(String name); }
【具体工厂】定义两个具体工厂类,实现工厂接口,如下:
package com.pichen.dp.creationalpattern.factorymethod; public class ChineseFatherFactory implements IFatherFactory{ @Override public Father createFather(String name) { return new ChineseFather(name); } }
package com.pichen.dp.creationalpattern.factorymethod; public class AmericanFatherFactory implements IFatherFactory{ @Override public Father createFather(String name) { return new AmericanFather(name); } }
【抽象产品】定义一个抽象产品类:
package com.pichen.dp.creationalpattern.factorymethod; public abstract class Father { private String name; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } public abstract void printName(); }
【具体产品】定义两个具体产品类,继承抽象产品:
package com.pichen.dp.creationalpattern.factorymethod; public class ChineseFather extends Father{ public ChineseFather(String name) { this.setName(name); } @Override public void printName() { System.out.println(this.getClass().getName() + ":" + this.getName()); } }
package com.pichen.dp.creationalpattern.factorymethod; public class AmericanFather extends Father{ public AmericanFather(String name) { this.setName(name); } @Override public void printName() { System.out.println(this.getClass().getName() + ":" + this.getName()); } }
【产品使用者】写个main函数,调用具体工厂类生产具体产品:
package com.pichen.dp.creationalpattern.factorymethod; public class Main { public static void main(String[] args) { IFatherFactory cnff = new ChineseFatherFactory(); Father cnFather = cnff.createFather("cn father"); cnFather.printName(); IFatherFactory usff = new AmericanFatherFactory(); Father usFather = usff.createFather("us father"); usFather.printName(); } }
标签:
原文地址:http://www.cnblogs.com/chenpi/p/5141376.html