模式定义
1.1 简单工厂模式(Simple Factory Pattern)
实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(继承自一个父类或接口)的实例。
1.1.1 模式结构
角色 | 说明 |
---|---|
Factory(工厂) | 负责创建所有具体产品类的实例 |
Product(抽象产品) | 负责描述所有实例所共有的公共接口 |
ConcreteProduct (具体产品) | 继承自抽象产品角色,返回的都是某一具体产品 |
1.1.2 模式优缺点
优点:
客户端与具体实现类解耦;
不用考虑对象的创建过程。
缺点:
工厂类集中了所有产品创建逻辑,一旦不能正常工作,整个系统都要受到影响;
系统类个数的递增,增加了系统的复杂度和理解难度;
系统扩展困难,不利于扩展和维护;
不符合开闭原则。
1.1.3 模式适用环境
工厂类创建的对象比较少,且不易变更;
客户端需要知道传入工厂类的参数,不需要关心如何创建对象。
1.1.4 模式代码
Product
//InterfaceTV.h
class InterfaceTV
{
public:
virtual void play() = 0;
};
ConcreteProduct
HaierTV
//HaierTV.h
#include "InterfaceTV.h"
class HaierTV :public InterfaceTV
{
public:
virtual void play();
};
//HaierTV.cpp
#include <iostream>
#include "HaierTV.h"
using namespace std;
void HaierTV::play()
{
cout << "Haier TV is playig..." << endl;
}
HisenseTV
//HisenseTV.h
#include "InterfaceTV.h"
class HisenseTV:public InterfaceTV
{
public:
virtual void play();
};
//HisenseTV.cpp
#include <iostream>
#include "HisenseTV.h"
using namespace std;
void HisenseTV::play()
{
cout << "Hisense TV is playig..." << endl;
}
Factory
#include "InterfaceTV.h"
#include "HisenseTV.h"
#include "HaierTV.h"
class TVFactory
{
public:
InterfaceTV * MakeTV(int type);
};
#include "TVFactory.h"
InterfaceTV * TVFactory::MakeTV(int type)
{
switch (type)
{
case 1:
return new HaierTV;
case 2:
return new HisenseTV;
default:
return nullptr;
}
}
Use
#include <iostream>
#include <stdio.h>
#include "InterfaceTV.h"
#include "TVFactory.h"
using namespace std;
void ShowResult(InterfaceTV& IntTV);
int main(int argc, char *argv[])
{
int type = 0;
cout << "Input an type:";
cin >> type;
TVFactory Tvf;
InterfaceTV *intTV = Tvf.MakeTV(type);
if (intTV == NULL)
{
return -1;
}
ShowResult(*intTV);
delete intTV;
cout << "Press any key to continue" << endl;
cin.get();
cin.get();
return 0;
}
void ShowResult(InterfaceTV& IntTV)
{
IntTV.play();
}
运行结果: