抽象工厂模式在工厂模式的基础上又增加了一层抽象。将抽象工厂模式与工厂模式比较,很明显是添加了一个新的抽象层。抽象工厂是一个创建其他工厂的超级工厂。我们可以把它叫做“工厂的工厂”。
代码:
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
;
// based on specific requirement
if
(sys ==
0
)
return
new
AMDFactory();
else
return
new
IntelFactory();
}
}