概述
- 定义:为创建一组相关或相互依赖的对象提供一个接口,而且无需指定它们的具体类。
- 抽象工厂模式又称为Kit模式。工厂方法模式是用来创建一个产品的等级结构的,而抽象工厂模式是用来创建多个产品的等级结构;针对多个业务品种、业务分类
- 是一种对象创建型模式。
- 学习难度:★★★★☆
- 使用频率:★★★★★
优缺点
类图
组成角色
- 抽象工厂类角色(AbstractFactory)
- 具体工厂类角色(ConcreteFactory)
- 抽象产品角色(AbstractProduct)
- 具体产品角色(ConcreteProduct)
Code Example
抽象工厂类角色(AbstractFactory)
public abstract class AbstractCarFactory {
public abstract Car createCar();
public abstract Bus createBus();
public static AbstractCarFactory getInstance(String className) {
AbstractCarFactory factory = null;
try {
factory = (AbstractCarFactory) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return factory;
}
}
具体工厂类角色(ConcreteFactory)
public class AudoFactory extends AbstractCarFactory {
@Override
public Bus createBus() {
return new AudoBus();
}
@Override
public Car createCar() {
return new AudoCar();
}
}
public class BenzFactory extends AbstractCarFactory {
@Override
public Bus createBus() {
return new BenzBus();
}
@Override
public Car createCar() {
return new BenzCar();
}
}
public class BmwFactory extends AbstractCarFactory {
@Override
public Bus createBus() {
return new BmwBus();
}
@Override
public Car createCar() {
return new BmwCar();
}
}
抽象产品角色(AbstractProduct)
public interface Car {
public void driver();
}
public interface Bus {
public void driver();
}
具体产品角色(ConcreteProduct)
public class AudoBus implements Bus {
public void driver() {
System.out.println("audo bus drive");
}
}
public class AudoCar implements Car {
public void driver() {
System.out.println("audo car drive");
}
}
public class BenzBus implements Bus {
public void driver() {
System.out.println("benz bus drive");
}
}
public class BenzCar implements Car {
public void driver() {
System.out.println("benz car drive");
}
}
public class BmwBus implements Bus {
public void driver() {
System.out.println("bmw bus drive");
}
}
public class BmwCar implements Car {
public void driver() {
System.out.println("bmw car drive");
}
}
客户端
public class AbstractFactory {
public static void main(String[] args) {
AbstractCarFactory factory = AbstractCarFactory.getInstance("factory.abstraction.BmwFactory");
Car car = factory.createCar();
Bus bus = factory.createBus();
car.driver();
bus.driver();
}
}