AbstractFactoryPattern(抽象工厂)

/**
 * 抽象工厂模式
 * 分为四部分
 * 1.产品接口
 * 2.产品实例
 * 3.工厂接口(生产同一个产品的不同等级,这里是主要区别)
 * 4.工厂实例
 * 工厂类最好用单例模式,但在这里主要是说明工厂方法,就不用单例了
 * 与工厂方法不同的地方是,可以生产不同等级的产品
 * @author TMAC-J
 *
 */
public class FactoryMethodPattern {
	/**
	 * 产品
	 *
	 */
	interface IProduct{
		void doSomething();
	}
	
	public class ConcreteProduct1 implements IProduct{
		
		public ConcreteProduct1() {}//等级为1
		
		public ConcreteProduct1(String a) {}//等级为2
		
		@Override
		public void doSomething() {
			System.out.println("concreteProduct do something!");
		}
	}
	
	public class ConcreteProduct2 implements IProduct{
		
		public ConcreteProduct2() {}//等级为1
		
		public ConcreteProduct2(String a) {}//等级为2
		
		@Override
		public void doSomething() {
			System.out.println("concreteProduct2 do something!");
		}
	}
	
	interface IFactory{
		IProduct createGrade1();//创建等级为1的产品
		IProduct createGrade2(String a);//创建等级为2的产品
	}
	
	public class ConcreteFactory1 implements IFactory{
		@Override
		public IProduct createGrade1() {
			IProduct product = new ConcreteProduct1();
			return product;
		}

		@Override
		public IProduct createGrade2(String a) {
			IProduct product = new ConcreteProduct1(a);
			return product;
		}
	}
	
	public class ConcreteFactory2 implements IFactory{
		@Override
		public IProduct createGrade1() {
			IProduct product = new ConcreteProduct2();
			return product;
		}

		@Override
		public IProduct createGrade2(String a) {
			IProduct product = new ConcreteProduct2(a);
			return product;
		}
	}
	
	public void test(){
		IFactory concreteFactory1 = new ConcreteFactory1();
		concreteFactory1.createGrade1();//生产等级1产品1
		concreteFactory1.createGrade2("a");//生产等级1产品1
		IFactory concreteFactory2 = new ConcreteFactory2();
		concreteFactory2.createGrade1();//生产等级1产品1
		concreteFactory2.createGrade2("a");//生产等级2产品1
	}
	
}

  

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