工厂方法模式定义:用于建立对象的接口,让子类决定实例化哪一个类。java
一种工厂模式的例子。ide
抽象产品类spa
public abstract class Product { public void method1(){ // 业务逻辑 } public abstract void method2(); }
具体产品类code
public class CreateProduct1 extends Product { @Override public void method2() { } }
public class CreateProduct extends Product { @Override public void method2() { } }
抽象工厂类对象
public abstract class Creator { public abstract < T extends Product> T createProduct(Class<T> c); }
具体工厂实现类接口
public class ConcreteCreator extends Creator { @Override public <T extends Product> T createProduct(Class<T> c) { Product product = null; try{ product = (Product)Class.forName(c.getName()).newInstance(); }catch (Exception e){ } return (T)product; } }
调用端get
public class Client { public static void main(String args[]){ Creator creator = new ConcreteCreator(); Product product = creator.createProduct(CreateProduct1.class); } }
工厂方法模式扩展产品
简单工厂模式(静态工厂模式)
io
public class ConcreteCreatorExt { public static <T extends Product> T createProduct(Class<T> c) { Product product = null; try{ product = (Product)Class.forName(c.getName()).newInstance(); }catch (Exception e){ } return (T)product; } }
2.替代单例模式class
public class Singleton1 { private Singleton1(){ } public void doSomething{ } }
public class SingletonFactory { private static Singleton1 singleton; static { try { Class c1 = Class.forName(Singleton1.class.getName()); Constructor constructor = c1.getConstructor(); constructor.setAccessible(true); singleton = (Singleton1)constructor.newInstance(); }catch (Exception e){ } } public static Singleton1 getSingleton(){ return singleton; } }
3.延迟初始化
一个对象被消费完毕后,并不马上释放,工厂类保持其初始化状态,等待再次被调用。
public class ProductFactory { private static final Map<String,Product> map = new HashMap(); public static synchronized Product createProduct(String type) throws Exception{ Product product = null; if(map.containsKey(type)){ product = map.get(type); }else{ product = new CreateProduct(); map.put(type,product); } return product; } }
抽象工厂模式:为建立一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体的实现类。
通用代码:
抽象product A
public abstract class AbstractProductA { // public void shareMethod(){ // 业务逻辑 } public abstract void method2(); }
具体实现类
public class ProductA1 extends AbstractProductA { @Override public void method2() { } }
public class ProductA2 extends AbstractProductA { @Override public void method2() { } }
抽象product B
public abstract class AbstractProductB { // public void shareMethod(){ // 业务逻辑 } public abstract void method2(); }
具体实现类
public class ProductB1 extends AbstractProductB { @Override public void method2() { } }
抽象建立类
public abstract class AbstractCreator { public abstract AbstractProductA createProductA(); public abstract AbstractProductB createProductB(); }
具体实现类
public class Creator1 extends AbstractCreator { @Override public AbstractProductA createProductA() { return new ProductA1(); } @Override public AbstractProductB createProductB() { return new ProductB1(); } }