您的位置:首页 > 编程语言 > C语言/C++

C++设计模式02——工厂方法模式

2017-12-30 22:04 253 查看
参考书:《大话设计模式》和《设计模式:可复用面向对象软件的基础》

1.意图

定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使一个类的实例化延迟到其子类。

2.别名

虚构造器(Virtual Constructor )

3.动机

框架使用抽象类定义和维护对象之间的关系。这些对象的创建通常也由框架负责。

4.适用性

在下列情况下可以使用Factory Method模式:

a)当一个类不知道它所必须创建的对象的类的时候

b)当一个类希望由它的子类来指定所创建的对象的时候。

c)当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候

5.结构

#include <iostream>

using namespace std;

class Product
{
public:
virtual void Show() = 0;
virtual ~Product()
{

}
};

class ProductA: public Product
{
public:
void Show()
{
cout << "I'm Product=================A" << endl;
}
};

class ProductB: public Product
{
public:
void Show()
{
cout << "I'm Product=================B" << endl;
}
};

class ProductC: public Product
{
public:
void Show()
{
cout << "I'm Product=================C" << endl;
}
};

class Factory
{
public:
virtual Product *CreateProduct() = 0;
virtual ~Factory()
{

}
};

class FactoryA: public Factory
{
public:
Product *CreateProduct()
{
return new ProductA();
}
};

class FactoryB: public Factory
{
public:
Product *CreateProduct()
{
return new ProductB();
}
};

class FactoryC: public Factory
{
public:
Product *CreateProduct()
{
return new ProductC();
}
};

int main()
{
Factory *factoryA = new FactoryA();
Product *productA = factoryA->CreateProduct();
productA->Show();

Factory *factoryB = new FactoryB();
Product *productB = factoryB->CreateProduct();
productB->Show();

Factory *factoryC = new FactoryC();
Product *productC = factoryC->CreateProduct();
productC->Show();

if(NULL != factoryA)
{
delete factoryA;
factoryA = NULL;
}

if(NULL != productA)
{
delete productA;
productA = NULL;
}

if(NULL != factoryB)
{
delete factoryB;
factoryB = NULL;
}

if(NULL != productB)
{
delete productB;
productB = NULL;
}

if(NULL != factoryC)
{
delete factoryC;
factoryC = NULL;
}

if(NULL != productC)
{
delete productC;
productC = NULL;
}

cout << "Hello World!" << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式