- Published on
设计模式(3)——工厂方法 Factory Method
- Authors
- Name
- Leon
三、Factory Method(工厂方法,对象创建型模式)
1. 问题:
- 当使用抽象基类或接口的子类时(多态),必须编写诸如 new xxx; 的代码。这带来了两个问题:
- 程序员必须知道子类的名称
- 扩展性和维护变得越来越困难
- 知道具体要实例化哪一个具体的子类
2. 功能:
- 定义创建对象的接口,封装了对象的创建
- 类的工作延迟到了子类中
3. 意图:
封装对象的创建过程,让系统与具体对象解耦。
4. 类图:
5. 中间层思考:
工厂类在客户(或程序员或系统)与产品(具体对象)的直接生成之间添加了一个中间层。
6. C++实现:
- 编写工厂接口、产品接口
- 工厂接口中编写生成产品的方法
Product* CreateProduct();
- 工厂接口实现类中编写具体生成的产品对象(延迟实例化)
Factory.h
// Factory.h
#ifndef _FACTORY_H_
#define _FACTORY_H_
class Product;
class Factory {
public:
virtual ~Factory() = 0;
virtual Product* CreateProduct() = 0;
protected:
Factory();
private:
};
class ConcreteFactory :public Factory
{
public:
~ConcreteFactory();
ConcreteFactory();
Product* CreateProduct();
protected:
private:
};
#endif // !_FACTORY_H_
Factory.cpp
//Factory.cpp
#include "Factory.h"
#include "Product.h"
#include <iostream>
using namespace std;
Factory::Factory()
{
}
Factory::~Factory() {}
ConcreteFactory::ConcreteFactory()
{
cout << "ConcreteFactory....." << endl;
}
ConcreteFactory::~ConcreteFactory()
{
}
Product* ConcreteFactory::CreateProduct()
{
return new ConcreteProduct();
}
Product.h
// Product.h
#ifndef _PRODUCT_H_
#define _PRODUCT_H_
class Product {
public:
virtual ~Product() = 0;
protected:
Product();
private:
};
class ConcreteProduct:public Product {
public:
~ConcreteProduct();
ConcreteProduct();
protected:
private:
};
#endif // !_PRODUCT_H_
Product.cpp
// Product.cpp
#include "Product.h"
#include "Factory.h"
#include <iostream>
using namespace std;
Product::Product() {
}
Product::~Product() {
}
ConcreteProduct::ConcreteProduct() {
cout << "concrete product..." << endl;
}
ConcreteProduct::~ConcreteProduct() {
}
main.cpp
// main.cpp
#include <istream>
#include "Factory.h"
#include "Product.h"
using namespace std;
int main(int argc, char* argv[])
{
Factory* fac = new ConcreteFactory();
Product* p = fac->CreateProduct();
return 0;
}