7.1 动机
在软件系统中,经常面临着“一系列相互依赖的对象”的创建工作;同时,由于需求的变化,往往存在更多系列对象的创建工作。
7.2 模式定义
提供一个接口,让该接口负责创建一系列“相关或者相互依赖的对象”,无需指定它们具体的类。
7.3 案例
电脑配件生产工厂生产内存、CPU等硬件设备,这些内存、CPU的品牌、型号并不一定相同,根据下面的“产品等级结构-产品族”示意图,使用抽象工厂模式实现电脑配件生产过程并绘制相应的类图,绘制类图并编程实现。
类图如下:
代码如下:
#pragma once
#include<string>
#include<iostream>
using namespace std;
class CPU {
public:
CPU(string brand) {
this->brand = brand;
}
string getBrand() {
return this->brand;
}
private:
string brand;
};
class RAM {
public:
RAM(string brand) {
this->brand = brand;
}
string getBrand() {
return this->brand;
}
private:
string brand;
};
class ComputerFactory {
public:
virtual CPU* createCPU() = 0;
virtual RAM* createRAM() = 0;
};
class PCFactory :public ComputerFactory {
public:
PCFactory() {
}
CPU* createCPU() {
return new CPU("PC-CPU");
}
RAM* createRAM() {
return new RAM("PC-RAM");
}
};
class MacFactory :public ComputerFactory {
public:
MacFactory() {
}
CPU* createCPU() {
return new CPU("Mac-CPU");
}
RAM* createRAM() {
return new RAM("Mac-RAM");
}
};
class Computer {
public:
Computer(CPU* cpu, RAM* ram) {
this->cpu = cpu;
this->ram = ram;
}
void printMyComputer() {
cout << "CPU:" << this->cpu->getBrand() << endl;
cout << "RAM:" << this->ram->getBrand() << endl;
}
private:
CPU* cpu;
RAM* ram;
};
void AF();
#include"AbstractFactory.h"
void AF() {
string argCPU = "PC";
string argRAM = "PC";
ComputerFactory* pcFactory = new PCFactory();
ComputerFactory* macFactory = new MacFactory();
while (1) {
cout << "You are building a computer..." << endl;
CPU* myCPU = nullptr;
RAM* myRAM = nullptr;
while (1) {
cout << "Please input your CPU(PC or Mac):";
cin >> argCPU;
if ("PC" == argCPU) {
myCPU = pcFactory->createCPU();
break;
}
else if ("Mac" == argCPU) {
myCPU = macFactory->createCPU();
break;
}
else {
cout << "sorry,please input PC or Mac..."<<endl;
}
}
while (1) {
cout << "Please input your RAM(PC or Mac):";
cin >> argRAM;
if ("PC" == argRAM) {
myRAM = pcFactory->createRAM();
break;
}
else if ("Mac" == argRAM) {
myRAM = macFactory->createRAM();
break;
}
else {
cout << "sorry,please input PC or Mac...";
}
}
Computer* computer = new Computer(myCPU, myRAM);
computer->printMyComputer();
cout << "==============================================" << endl;
}
}
运行结果:
7.4 工厂方法在主流框架中的应用
- Django 框架中的视图函数通常也是通过工厂方法来创建的。在 Django 中,视图函数负责处理客户端请求,并返回相应的 HTTP 响应。通过工厂方法,可以根据 URL 映射关系动态地选择和创建对应的视图函数。
- 在 Java Servlet API 中,Servlet 容器使用工厂方法来动态地实例化 Servlet 对象。当客户端请求到达时,Servlet 容器根据请求的 URL 映射关系创建对应的 Servlet 对象,从而处理客户端请求。
- 在 Spring 框架中,工厂方法模式被广泛应用于依赖注入(DI)和控制反转(IoC)的实现中。Spring 使用工厂方法来创建和管理各种类型的 bean(组件),这些 bean 可以是单例、原型、会话、请求或其他作用域的对象。