定义
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使得一个类的实例化延迟(目的:解耦,手段:虚函数)到子类。
应用场景
- 在软件系统中,经常面临着创建对象的工作;由于需求的变化,需要创建的对象的具体类型经常变化。
- 如何应对这种变化?如何绕过常规的对象创建方法(new),提供一种“封装机制"来避免客户程序和这种具体对象创建工作的紧耦合?
结构
代码示例
//Factory.h
/****************************************************/
#ifndef FACTORY_H
#define FACTORY_H
#include<iostream>
using namespace std;
class Shape
{
public:
Shape() {};
virtual ~Shape() {};
virtual void draw() = 0;
enum Shape_type{ Rectangle , Square, Circle};
};
class Rectangle :Shape
{
public:
Rectangle() {};
~Rectangle() {};
void draw() { cout << "Inside Rectangle::draw() method." << endl; };
};
class Square :Shape
{
public:
Square() {};
~Square() {};
void draw() { cout << "Inside Square::draw() method." << endl; };
};
class Circle :Shape
{
public:
Circle() {};
~Circle() {};
void draw() { cout << "Inside Circle::draw() method." << endl; };
};
class ShapeFactory
{
public:
ShapeFactory() {};
~ShapeFactory() {};
Shape* getShapeFactory(Shape::Shape_type type);
};
Shape* ShapeFactory::getShapeFactory(Shape::Shape_type type)
{
switch (type)
{
case Shape::Rectangle:
return (Shape*)new Rectangle();
case Shape::Square:
return (Shape*)new Square();
case Shape::Circle:
return (Shape*)new Circle();
default:
return NULL;
}
}
#endif
//test.cpp
/****************************************************/
#include <iostream>
#include <string>
#include "Factory.h"
int main()
{
ShapeFactory shapefac;
Shape *t1 =(Shape*) shapefac.getShapeFactory(Shape::Circle);
Shape *t2 = (Shape*)shapefac.getShapeFactory(Shape::Circle);
Shape *t3 = (Shape*)shapefac.getShapeFactory(Shape::Circle);
t1->draw();
t2->draw();
t3->draw();
delete t1;
t1 = NULL;
delete t2;
t2 = NULL;
delete t3;
t3= NULL;
return 0;
}
运行结果
要点总结
- Factory Method模式用于隔离类对象的使用者和具体类型之间的耦合关系。面对一个经常变化的具体类型,紧耦合关系(new)会导致软件的脆弱。
- Factory Method模式通过面向对象的手法,将所要创建的具体对象工作延迟到子类,从而实现一种扩展(而非更改)的策略,较好地解决了这种紧耦合关系。
- Factory Method模式解决“单个对象’的需求变化。缺点在于要求创建方法/参数相同。