欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

漫谈设计模式(四)工厂(Factory)模式

程序员文章站 2024-01-05 21:48:40
...
有类型区分的工厂模式


Factory类


package com.model.factory;

public interface Factory {

	int TYPE1 = 10000;
	int TYPE2 = 20000;
	int TYPE3 = 30000;
	int TYPE4 = 40000;
	int TYPE5 = 50000;

	Product createProduct(Integer type);

}



package com.model.factory;

public interface Product {

}




package com.model.factory;

public class ConcreteFactory implements Factory {



	@Override
	public Product createProduct(Integer type) {
		Product product=null;
		switch (type) {
		case TYPE1:
			product=new WoodProduct();
			break;

		default:
			product= new ConcreteProduct();
			break;
		}
		return product;
	}


}




package com.model.factory;

public class ConcreteProduct implements Product {

}





package com.model.factory;

public class WoodProduct implements Product {

	
}




测试类

package com.model.factory;

public class Client {

	private Factory factory;

	public Client(Factory factory) {
		this.factory = factory;
	}

	public void doSomething() {
		Product product = factory.createProduct(Factory.TYPE1);
		// do someThing
	}

	public static void main(String[] args) {
		Client client = new Client(new ConcreteFactory());
		client.doSomething();
	}

}






上一篇:

下一篇: