工厂方法模式

工厂是一个含义模糊的术语,表示可以创建一些东西的函数、方法或类。最常见的情况下,工厂创建的是对象
工厂方法是一种创建型设计模式,其在父类中提供一个创建对象的方法,允许子类决定实例化对象的类型。
个人理解:基类中声明一个虚函数(工厂方法:返回对象的方法)不同派生类重写该工厂方法实现不同功能(创建不同对象)。即同一个工厂(基类工厂方法)可以产生不同对象。完全使用了继承的特性。

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

学习链接:工厂方法模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值