简单工厂模式
简单工厂模式属于创建型模式,创建型模式主要关注点是“怎样创建对象?”,它的主要特点是“将创建对象与使用分离”。这样可以降低系统的耦合度,使用者不需要关心对象创建的细节,对象的创建由相关的工厂去完成。
简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或者接口)的实例。
该模式中包含了一下三个角色:
shapeFactory.cpp
class shapeFacetory { public: shape* shapeFacetory::getShape(std::string shapeType) { if (shapeType == "circle") { return new circle(); } else if (shapeType == "rectangle") { return new rectangle(); } else if (shapeType == "square") { return new square(); } } }:
shape抽象类
class shape { public: virtual void draw() = 0; };
circle.cpp、rectangle.cpp、square.cpp
class circle : public shape { public: std::cout << "Inside Circle::draw() method."; };
class rectangle : public shape { public: std::cout << "Inside Rectangle::draw() method."; };
class square : public shape { public: std::cout << "Inside Square::draw() method."; };
#include "shape.h" #include "circle.h" #include "square.h" #include "rectangle.h" #include "shapeFactory.h" int main() { shapeFacetory* factory = new shapeFacetory; shape* ps = factory->getShape("circle"); ps->draw(); return 0; }
源码地址:https://github.com/zhousong666/TestProject/tree/master/DesignModel/SimpleFactory
优质内容筛选与推荐>>