工厂模式是专门负责将大量共同接口的类实例化,而且事先不知道每次是要实例哪一个类的模式。它定义一个用于创建对象的接口,由子类决定实例化哪一个类。
我们把java工厂模式归纳为两种:简单工厂模式和抽象工厂模式。
1、简单工厂模式
简单工厂模式的结构
代码演示:
// 产品接口
public interface Product {
public void getName();
}
// 具体产品A
public class ProductA implements Product {
public void getName() {
System.out.println(" I am ProductA ");
}
}
// 具体产品B
public class ProductB implements Product {
public void getName() {
System.out.println(" I am ProductB ");
}
}
// 工厂类
public class ProductCreator {
public Product createProduct(String type) {
if (" A ".equals(type)) {
return new ProductA();
}
if (" B ".equals(type)) {
return new ProductB();
} else
return null;
}
public static void main(String[] args) {
ProductCreator creator = new ProductCreator();
creator.createProduct(" A ").getName();
creator.createProduct(" B ").getName();
}
}
实用范围:
• 在编码时不能预见需要创建哪一种类的实例。
• 一个类使用它的子类来创建对象。
• 开发人员不希望创建了哪个类的实例以及如何创建实例的信息暴露给外部程序。
2、抽象工厂模式
抽象工厂模式可以说是简单工厂模式的扩展,它们主要的区别在于需要创建对象的复杂程度上。
在抽象工厂模式中,抽象产品可能是一个或多个,从而构成一个或多个产品族。 在只有一个产品族的情况下,抽象工厂模式实际上退化到工厂方法模式。
抽象工厂模式的结构
代码
// 产品 Plant接口
public interface Plant {
}
// 具体产品PlantA,PlantB
public class PlantA implements Plant {
public PlantA() {
System.out.println(" create PlantA ! ");
}
public void doSomething() {
System.out.println(" PlantA do something ");
}
}
public class PlantB implements Plant {
public PlantB() {
System.out.println(" create PlantB ! ");
}
public void doSomething() {
System.out.println(" PlantB do something ");
}
}
// 产品 Fruit接口
public interface Fruit {
}
// 具体产品FruitA,FruitB
public class FruitA implements Fruit {
public FruitA() {
System.out.println(" create FruitA ! ");
}
public void doSomething() {
System.out.println(" FruitA do something ");
}
}
public class FruitB implements Fruit {
public FruitB() {
System.out.println(" create FruitB ! ");
}
public void doSomething() {
System.out.println(" FruitB do something ");
}
}
// 抽象工厂方法
public interface AbstractFactory {
public Plant createPlant();
public Fruit createFruit();
}
// 具体工厂方法
public class FactoryA implements AbstractFactory {
public Plant createPlant() {
return new PlantA();
}
public Fruit createFruit() {
return new FruitA();
}
}
public class FactoryB implements AbstractFactory {
public Plant createPlant() {
return new PlantB();
}
public Fruit createFruit() {
return new FruitB();
}
}
小结 在以下情况下,应当考虑使用抽象工厂模式。
首先,一个系统应当不依赖于产品类实例被创立,组成,和表示的细节。这对于所有形态的工厂模式都是重要的。
其次,这个系统的产品有多于一个的产品族。
第三,同属于同一个产品族的产品是设计成在一起使用的。这一约束必须得在系统的设计中体现出来。
最后,不同的产品以一系列的接口的面貌出现,从而使系统不依赖于接口实现的细节。
其中第二丶第三个条件是我们选用抽象工厂模式而非其它形态的工厂模式的关键性条件。