工厂模式
1 简单工厂模式
package factory;
public interface Product {
}
public class ProductA implements Product{
public ProductA() {
System.out.println("ProductA");
}
}
package factory;
public class ProductB implements Product {
public ProductB() {
System.out.println("ProductB");
}
}
package factory;
public class Factory {
public static Product create(String str)
{
if(str.equalsIgnoreCase("ProductA"))
{
return new ProductA();
}
else
if(str.equalsIgnoreCase("ProductB"))
{
return new ProductB();
}
return null;
}
}
- benefit : 将产品创建分离
- shortcoming : 每增加一个产品就要修改factory
2 工厂方法模式
package factoryMehtod;
public interface Factory {
public Product createProduct();
}
package factoryMehtod;
public class FactoryA implements Factory {
public Product createProduct()
{
return new ProductA();
}
}
生产ProductB类似
现在生产产品A:
Factory factory;
factory = new FactoryA();
factory.createProduct();
- benefit: 支持任意类型产品的扩展
- shortcoming: 如果产品种类很多,就需要生产很多工厂类
3 抽象工厂方法模式
package abstractFactory;
public interface Gift {
}
package abstractFactory;
public class GiftA implements Gift {
public GiftA()
{
System.out.println("GiftA");
}
}
package abstractFactory;
public class GiftB implements Gift {
public GiftB()
{
System.out.println("GiftB");
}
}
package abstractFactory;
public interface Factory {
public Product createProduct();
public Gift createGift();
}
package abstractFactory;
public class Client {
public static void main(String[] args) {
Factory factory;
factory = new FactoryA();
factory.createProduct();
factory.createGift();
factory = new FactoryB();
factory.createProduct();
factory.createGift();
}
}
- 抽象工厂模式中我们可以定义实现不止一个接口,一个工厂也可以生成不止一个产品类,抽象工厂模式较好的实现了“开放-封闭”原则,是三个模式中较为抽象,并具一般性的模式。我们在使用中要注意使用抽象工厂模式的条件。
- 这样看来抽象工厂要更加灵活些