工厂模式
定义一个用于创建对象的接口,让子类决定实例化哪一个类。
适用场景
1、当一个类不知道它所必须创建的对象的类的时候。
2、当一个类希望由它的子类来指定它所创建的对象的时候。
3、 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类
是代理者这一信息局部化的时候。
采用菜鸟教程的例子,这里用C++实现
#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;
}
}
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;
}
在visual studio 2015上运行结果: