工厂是一个含义模糊的术语,表示可以创建一些东西的函数、方法或类。最常见的情况下,工厂创建的是对象。
工厂方法是一种创建型设计模式,其在父类中提供一个创建对象的方法,允许子类决定实例化对象的类型。
个人理解:基类中声明一个虚函数(工厂方法:返回对象的方法),不同派生类重写该工厂方法实现不同功能(创建不同对象)。即同一个工厂(基类工厂方法)可以产生不同对象。完全使用了继承的特性。
#include <iostream>
#include <string>
using namespace std;
// 工厂可以创建的产品基类
class Employee {
public:
Employee() = default;
// 不同产品的相同接口sleep实现不同操作
virtual void sleep() = 0;
};
// 工厂可以创建的ITEmployee产品
class ITEmployee : public Employee {
public:
ITEmployee(string name) :m_name(name){}
void sleep() { cout<<"I sleep on computer"<<endl; }
private:
string m_name;
};
// 工厂可以创建的AccountEmployee产品
class AccountEmployee : public Employee {
public:
ccountEmployee(string name) :m_name(name){}
void sleep() { cout<<"I sleep with money"<<endl; }
private:
string m_name;
};
// Department为工厂,工厂方法定义了一个方法,且必须使用该方法
// 代替通过直接调用构造函数来创建对象(new操作符)的方式。
// 子类可重写该方法来更改将被创建的对象所属类。
class Department {
public:
Department() = default;
// create_employee即为工厂方法:
virtual Employee* create_employee(string name) = 0;
};
class ITDepartment : public Department {
public:
ITDepartment() = default;
// 重载工厂方法以创建不同的产品
Employee* create_employee(string name) { return new ITEmployee(name); }
};
class AccountDepartment : public Department {
public:
AccountDepartment() = default;
// 重载工厂方法以创建不同的产品
Employee* create_employee(string name) { return new AccountEmployee(name); }
};
int main()
{
Department* department1 = new ITDepartment();
Employee* employee1 = department1->create_employee("zzy"); employee1->sleep();
Department* department2 = new AccountDepartment();
Employee* employee2 = department2->create_employee("zzy"); employee2->sleep();
getchar();
}
学习链接:工厂方法模式