抽象工厂模式例子
通过一个例子,来加深对抽象工厂的理解。
//CPU工厂接口
public interface CPUFactory {
public void createCPU();
}
//IntelCPU工厂
public class IntelCPU implements CPUFactory {
@Override
public void createCPU() {
System.out.println("Intel CPU");
}
}
//AMDCPU工厂
public class AMDCPU implements CPUFactory {
@Override
public void createCPU() {
System.out.println("AMD CPU");
}
}
//创建抽象工厂类接口
public interface Provider {
public CPUFactory createCPUFactory();
}
public class InterCPUFactory implements Provider {
@Override
public CPUFactory createCPUFactory() {
return new InterCPU();
}
}
public class AMDCPUFactory implements Provider {
@Override
public CPUFactory createCPUFactory() {
return new AMDCPU();
}
}
public static void main(String[] args) {
//创建一个生产CPU工厂的工厂
Provider cpufactory = new InterCPUFactory();
//通过CPU工厂的工厂创建一个IntelCPU工厂
CPUFactory intelcpu = cpufactory.createCPUFactory();
//IntelCPU工厂生产intelCPU
intelcpu.createCPU();
}