`

设计模式:抽象工厂模式

阅读更多

1、简述

抽象工厂模式在工厂模式的基础上多添加了一层抽象,跟工厂模式比较一下,这个很容易看得出来。抽象工厂是一个工厂的父类,用来创建其他工厂。可以说是生产工厂的工厂。

2、抽象工厂类图



 3、抽象工厂实例代码

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();
    }
}

 

  • 大小: 20.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics