第0章:简介
简单工厂模式定义:提供一个创建对象实例的功能,而无需关心其具体实现。被创建实例的类型可以是接口、抽象类或具体类
简单工厂模式的实质:选择实现
参考:http://chjavach.iteye.com/blog/800325 ,研磨设计模式(书籍),大话设计模式(书籍)
模式图:
待补充
第1章:实践
(1)接口类(Intf.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 接口 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:24 */ public interface Intf { public void someMethod(); } |
(2)实现类A(IntfImplA.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 实现类A * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:28 */ public class IntfImplA implements Intf { @Override public void someMethod() { System.out.println("实现类A"); } } |
(3)实现类B(IntfImplB.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 实现类B * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:28 */ public class IntfImplB implements Intf { @Override public void someMethod() { System.out.println("实现类B"); } } |
(4)简单工厂类(Factory.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 简单工厂 * * 简单工厂模式定义:提供一个创建对象实例的功能,而无需关心其具体实现。被创建实例的类型可以是接口、抽象类或具体类 * 简单工厂模式的实质:选择实现 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:18 */ public class Factory { /** * 创建对象的方法 * @param implType 实体标识 * @return */ public static Intf create(int implType){ Intf intf = null; if(implType == 1){ intf = new IntfImplA(); }else if(implType == 2){ intf = new IntfImplB(); } return intf; } } |
(5)客户端测试类(Client.java)
package com.mcc.core.designPattern.build.simpleFactory; /** * 客户端测试 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-9 上午12:39 */ public class Client { public static void main(String args[]){ //工厂生产A对象 Intf intfA = Factory.create(1); intfA.someMethod(); //工厂生产B对象 Intf intfB = Factory.create(2); intfB.someMethod(); } } |