工厂
工厂用来封装对象的创建。
简单工厂模式
一、模式概念
从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。
二、uml图
工厂方法模式
一、模式概念
是定义一个创建产品对象的工厂接口,让子类决定实例化哪一个类,将实际创建工作推迟到子类当中。
二、uml图
抽象工厂模式
一、模式概念
提供一个接口,用于创建相关或依赖对象的家族,而不用明确指定具体的类型
二、uml图
抽象工厂具有一般性
show code
产品家族
/** * Created by supertool on 15-4-21. */ public interface IProductorA { }
/** * Created by supertool on 15-4-21. */ public class ProductorA1 implements IProductorA{ public ProductorA1(){ System.out.println("create A1"); } public void doOther(){ System.out.println("A1 other"); } }
/** * Created by supertool on 15-4-21. */ public class ProductorA2 implements IProductorA { public ProductorA2(){ System.out.println("create A2"); } public void doOther(){ System.out.println("A2 other"); } }
/** * Created by supertool on 15-4-21. */ public interface IProductorB { }
/** * Created by supertool on 15-4-21. */ public class ProductorB1 implements IProductorB { public ProductorB1(){ System.out.println("create B1"); } public void doOther(){ System.out.println("B1 other"); } }
/** * Created by supertool on 15-4-21. */ public class ProductorB2 implements IProductorB{ public ProductorB2(){ System.out.println("create B2"); } public void doOther(){ System.out.println("B2 other"); } }
抽象工厂
/** * Created by supertool on 15-4-21. */ public interface AbstractFactory { public IProductorA createA(); public IProductorB createB(); }
public class ConcreteFactory1 implements AbstractFactory { @Override public IProductorA createA() { return new ProductorA1(); } @Override public IProductorB createB() { return new ProductorB1(); } }
/** * Created by supertool on 15-4-21. */ public class ConcreteFactory2 implements AbstractFactory { @Override public IProductorA createA() { return new ProductorA2(); } @Override public IProductorB createB() { return new ProductorB2(); } }
public class FactoryTest { public static void main(String[] args) { AbstractFactory factory1 = new ConcreteFactory1(); System.out.println(factory1.createA()); System.out.println(factory1.createB()); } }
create A1
com.miaozhen.study.mr.model.factory.abstractfactory.ProductorA1@12edcd21
create B1
com.miaozhen.study.mr.model.factory.abstractfactory.ProductorB1@34c45dca