FactoryMethodPattern(工厂方法)

/**
 * 工厂方法模式
 * 分为四部分
 * 1.产品接口
 * 2.产品实例
 * 3.工厂接口
 * 4.工厂实例
 * 工厂类最好用单例模式,但在这里主要是说明工厂方法,就不用单例了
 * @author TMAC-J
 *
 */
public class FactoryMethodPattern {
	/**
	 * 产品
	 *
	 */
	interface IProduct{
		void doSomething();
	}
	
	public class ConcreteProduct1 implements IProduct{
		@Override
		public void doSomething() {
			System.out.println("concreteProduct do something!");
		}
	}
	
	public class ConcreteProduct2 implements IProduct{
		@Override
		public void doSomething() {
			System.out.println("concreteProduct2 do something!");
		}
	}
	
	interface IFactory{
		IProduct create();
	}
	
	public class ConcreteFactory1 implements IFactory{
		@Override
		public IProduct create() {
			IProduct product = new ConcreteProduct1();
			return product;
		}
	}
	
	public class ConcreteFactory2 implements IFactory{
		@Override
		public IProduct create() {
			IProduct product = new ConcreteProduct2();
			return product;
		}
	}
	
	public void test(){
		IFactory concreteFactory1 = new ConcreteFactory1();
		concreteFactory1.create();//生产产品1
		IFactory concreteFactory2 = new ConcreteFactory2();
		concreteFactory2.create();//生产产品1
	}
	
}

  

posted @ 2016-12-27 17:36  麦子TMAC  阅读(164)  评论(0编辑  收藏  举报