概述
抽象工厂模式是工厂方法模式的升级版本,他用来创建一组相关或者相互依赖的对象。比如宝马320系列使用空调型号A和发动机型号A,而宝马230系列使用空调型号B和发动机型号B,那么使用抽象工厂模式,在为320系列生产相关配件时,就无需制定配件的型号,它会自动根据车型生产对应的配件型号A。
产品类
interface CPU {
}
class CPU1 implements CPU {
public CPU1() {
System.out.println("生产CPU型号1");
}
}
class CPU2 implements CPU {
public CPU2() {
System.out.println("生产CPU型号2");
}
}
/**
* 抽象产品类:显示器
*/
interface Monitor {
}
class Monitor1 implements Monitor {
public Monitor1() {
System.out.println("生产显示器型号1");
}
}
class Monitor2 implements Monitor {
public Monitor2() {
System.out.println("生产显示器型号2");
}
}
class Computers {
CPU cpu;
Monitor monitor;
public Computers(CPU cpu, Monitor monitor) {
this.cpu = cpu;
this.monitor = monitor;
}
public CPU getCpu() {
return cpu;
}
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
public Monitor getMonitor() {
return monitor;
}
public void setMonitor(Monitor monitor) {
this.monitor = monitor;
}
}
创建工厂类
interface ComputerFactorys {
Computers createComputer();
}
class DellFactory implements ComputerFactorys {
@Override
public Computers createComputer() {
CPU cpu1 = new CPU1();
Monitor monitor1 = new Monitor1();
return new Computers(cpu1, monitor1);
}
}
class HPFactorys implements ComputerFactorys {
@Override
public Computers createComputer() {
CPU cpu2 = new CPU2();
Monitor monitor2 = new Monitor2();
return new Computers(cpu2, monitor2);
}
}
客户
public class Customer {
public static void main(String[] args) {
DellFactory dellFactory = new DellFactory();
Computers computer = dellFactory.createComputer();
HPFactorys hpFactorys = new HPFactorys();
Computers computer1 = hpFactorys.createComputer();
}
}