1、C++设计模式——工厂模式(菜鸟教程例子)
原例网址:工厂模式(菜鸟教程)
工厂模式
工厂模式(Factory Pattern)这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
#include "iostream" #include "string" using namespace std; //步骤1 创建一个接口 class Shape { public: virtual void draw() = 0; }; //步骤2 创建实现接口的实体类 class Circle : public Shape { public: void draw() { cout << "Inside Circle::draw() method." << endl; } }; class Square : public Shape { public: void draw() { cout << "Inside Square::draw() method." << endl; } }; class Rectangle : public Shape { public: void draw() { cout << "Inside Rectangle::draw() method." << endl; } }; //步骤3 创建一个工厂,生成基于给定信息的实体类的对象 class ShapeFactory { public: Shape* getShape(string shapeType) { if ( shapeType == "CIRCLE" ) { return new Circle; } else if ( shapeType == "SQUARE" ) { return new Square; } else if ( shapeType == "RECTANGLE" ) { return new Rectangle; } else { cout << "未知的shapeType" << endl; return NULL; } } }; //步骤4 使用该工厂,通过传递类型信息来获取实体类的对象 void main() { ShapeFactory* shapeFactory = NULL; Shape* shape1 = NULL; shapeFactory = new ShapeFactory; //获取 Circle 的对象,并调用它的 draw 方法 shape1 = shapeFactory->getShape("CIRCLE"); //调用 Circle 的 draw 方法 shape1->draw(); //删除 Circle 的对象 delete shape1; //获取 Square 的对象,并调用它的 draw 方法 shape1 = shapeFactory->getShape("SQUARE"); //调用 Square 的 draw 方法 shape1->draw(); //删除 Square 的对象 delete shape1; //获取 Rectangle 的对象,并调用它的 draw 方法 shape1 = shapeFactory->getShape("RECTANGLE"); //调用 Rectangle 的 draw 方法 shape1->draw(); //删除 Rectangle 的对象 delete shape1; delete shapeFactory; system("pause"); }
运行结果: