抽象工厂模式为工厂模式添加了一个抽象层,是创建其它工厂的超级工厂,也称为工厂的工厂。
Abstract Factory class diagram
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package client;
interface CPU
{
void process();
}
interface CPUFactory
{
CPU produceCPU();
}
class AMDFactory implements CPUFactory
{
public CPU produceCPU()
{
return new AMDCPU();
}
}
class IntelFactory implements CPUFactory
{
public CPU produceCPU()
{
return new IntelCPU();
}
}
class AMDCPU implements CPU
{
public void process()
{
System.out.println("AMD is processing....");
}
}
class IntelCPU implements CPU
{
public void process()
{
System.out.println("Intel is processing...");
}
}
class Computer
{
CPU cpu;
public Computer(CPUFactory factory)
{
cpu = factory.produceCPU();
cpu.process();
}
}
public class Client
{
public static void main(String[] args)
{
new Computer(createSpecificFactory());
}
public static CPUFactory createSpecificFactory()
{
int sys = 0;
if (sys == 0) return new AMDFactory();
else return new IntelFactory();
}
}