工厂模式分为:工厂方法模式和抽象工厂模式。
工厂方法模式
先介绍下工厂方法模式,工厂方法从字面上来理解就是一个方法,根据传递的参数来构造对象。
下面是一个例子:我们向工厂传递 “boy”,则会返回一个男员工,反之则返回女员工。
工厂方法类图
抽象工厂方法代码
interface Human {
public void Talk();
public void Walk();
}
class Boy implements Human{
@Override
public void Talk() {
System.out.println("Boy is talking...");
}
@Override
public void Walk() {
System.out.println("Boy is walking...");
}
}
class Girl implements Human{
@Override
public void Talk() {
System.out.println("Girl is talking...");
}
@Override
public void Walk() {
System.out.println("Girl is walking...");
}
}
public class HumanFactory {
public static Human createHuman(String m){
Human p = null;
if(m.equals("boy")){
p = new Boy();
}else if(m.equals("girl")){
p = new Girl();
}
return p;
}
}
在jdk中的应用:
java.util.Calendar 类为例
java.util.Calendar - getInstance()
java.util.Calendar - getInstance(TimeZone zone)
java.util.Calendar - getInstance(Locale aLocale)
java.util.Calendar - getInstance(TimeZone zone, Locale aLocale)
java.text.NumberFormat - getInstance()
java.text.NumberFormat - getInstance(Locale inLocale)
抽象工厂模式
抽象工厂模式是在工厂模式的基础上增加的一层抽象概念。如果比较抽象工厂模式和工厂模式,我们不难发现前者只是增加了一层抽象的概念。抽象工厂是一个父类工厂,可以创建其它工厂类。故我们也叫它“工厂的工厂”。
抽象工厂模式类图
抽象工厂代码
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();
}
}