6.1 动机
在软件系统中,经常面临着创建对象的工作;由于需求的变化,需要创建的对象的具体类型经常变化。
6.2 模式定义
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使得一个类的实例化延迟(目的:解耦,手段:虚函数)到子类。
6.3 案例
① 简单工厂模式:使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,请实现该场景。现需要增加一个新的Robot类,如果传入参数R,则返回一个Robot对象,对代码进行修改并注意女娲的变化。
类图如下:
代码如下:
#pragma once
#include<string>
#include<iostream>
using namespace std;
class Person {
public:
Person(string type) {
this->type = type;
}
string getType() {
return this->type;
}
private:
string type;
};
class Man :public Person {
public:
Man() :Person("Man") {
}
};
class Woman :public Person {
public:
Woman() : Person("Woman") {
}
};
class Robot :public Person {
public:
Robot() :Person("Robot") {
}
};
class Nvwa {
public:
Person* create(char arg);
};
void SF();
#include"simpleFactory.h"
Person* Nvwa::create(char arg) {
Person *ret;
switch (arg)
{
case 'M':
ret = new Man();
break;
case 'W':
ret = new Woman();
break;
case 'R':
ret = new Robot();
break;
default:
ret = nullptr;
break;
}
return ret;
}
void SF() {
Nvwa nvwa;
char arg = 'W';
while (1) {
cout << "Nvwa is making Person:";
cin >> arg;
Person* person = nvwa.create(arg);
cout << "Nvwa made a " + person->getType() << endl;
}
}
运行结果:
② 工厂方式模式:海尔工厂(Haier)生产海尔空调(HaierAirCondition),美的工厂(Midea)生产美的空调(MideaAirCondition) 。使用工厂方法模式描述该场景,绘制类图并编程实现。
类图如下:
代码如下:
#pragma once
#include<string>
#include<iostream>
using namespace std;
// 空调基类
class AirCondition {
public:
AirCondition(string name) {
this->name = name;
}
string getName() {
return this->name;
}
private:
string name;
};
// 海尔空调
class HaierAirCondition :public AirCondition {
public:
HaierAirCondition() :AirCondition("HaierAirCondition") {
}
};
// 美的空调
class MideaAirCondition :public AirCondition {
public:
MideaAirCondition() :AirCondition("MideaAirCondtion") {
}
};
// 空调工厂基类
class AirConditionFactory {
public:
AirConditionFactory(string type) {
this->type = type;
}
string getType() {
return this->type;
}
virtual AirCondition* makeAirCondition() = 0;
private:
string type;
};
// 海尔工厂
class HaierFactory :public AirConditionFactory {
public:
HaierFactory():AirConditionFactory("Haier") {
}
AirCondition* makeAirCondition() {
return new HaierAirCondition();
}
};
// 美的工厂
class MideaFactory :public AirConditionFactory {
public:
MideaFactory() :AirConditionFactory("Midea") {
}
AirCondition* makeAirCondition() {
return new MideaAirCondition();
}
};
void FM();
#include"FactoryMethod.h"
void FM() {
char arg = 'H';
AirConditionFactory* haier = new HaierFactory();
AirConditionFactory* midea = new MideaFactory();
AirCondition* ac = nullptr;
while (1) {
cout << "You are choosing to buy an air conditioner:";
cin >> arg;
switch (arg)
{
case 'H':
ac = haier->makeAirCondition();
break;
case 'M':
ac = midea->makeAirCondition();
break;
default:
break;
}
if (ac != nullptr) {
cout << "You get a " << ac->getName() << endl;
}
else {
cout << "sorry,please input H or M" << endl;
}
}
}
运行结果: