18 Jul 2014

Java设计模式:抽象工厂

注:本文为译文,原文出处java-design-patterns-in-stories

抽象工厂模式在工厂模式基础上添加了另外一个抽象层. 如果将抽象工厂和工厂模式作比较的话, 被添加的抽象层是显而易见的. 抽象工厂是一个用于创建其他工厂的父工厂. 姑且称之为”工厂们的工厂”.

抽象工厂类图

abstract-factory-design-pattern

抽象工厂的Java示例

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

现实中的用例

事实上, 抽象工厂是流行框架中非常重要的理论, 如下是stackoverflow中的一个经典问题:abstract-factory-pattern-on-top-of-ioc


Tags:
0 comments