工厂模式:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。工厂模式属于创建型模式,其主要解决的是计划在不同条件下创建不同实例时接口选择的问题。
实现:
1、创建接口
1 class IShape 2 { 3 public: 4 virtual void draw() = 0; 5 virtual ~IShape() {}; 6 };
2、创建接口实体类
1 class Rectangle :public IShape 2 { 3 virtual void draw(); 4 }; 5 6 class Square : public IShape 7 { 8 virtual void draw(); 9 }; 10 11 void Rectangle::draw() 12 { 13 cout << "this is Rectangle" << endl; 14 } 15 16 void Square::draw() 17 { 18 cout << "this is Square" << endl; 19 }
3、创建工厂类接口
1 class IShapeFactory 2 { 3 public: 4 virtual IShape* createShape() = 0; 5 virtual ~IShapeFactory() {}; 6 };
4、创建工厂类接口实体
1 class RectangleFactory : public IShapeFactory 2 { 3 public: 4 virtual IShape* createShape(); 5 }; 6 7 class SquareFactory : public IShapeFactory 8 { 9 public: 10 virtual IShape* createShape(); 11 }; 12 13 IShape* RectangleFactory::createShape() 14 { 15 return new Rectangle(); 16 } 17 18 IShape* SquareFactory::createShape() 19 { 20 return new Square(); 21 }
5、使用工厂类
int main() { IShapeFactory* factory = new RectangleFactory(); IShape* rectangle = factory->createShape(); rectangle->draw(); delete factory; factory = new SquareFactory(); IShape* square = factory->createShape(); square->draw(); delete factory; delete rectangle; delete square; return 0; }
通过使用工厂类的接口,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。如果不使用工厂类的接口,而是直接创建对应类的工厂类,这样的话IShape还是间接的对具体的类产生了依赖。相反使用了工厂类的接口,接口IShape只和接口IShapeFactory产生依赖,所以工厂模式解除了对象的使用者和具体类型间的耦合关系。