工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
实现
我们将创建一个
Shape
接口和实现
Shape
接口的实体类。下一步是定义工厂类
ShapeFactory
。
FactoryPatternDemo
,我们的演示类使用
ShapeFactory
来获取
Shape
对象。它将向
ShapeFactory
传递信息(
CIRCLE / RECTANGLE / SQUARE
),以便获取它所需对象的类型。
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: InterfaceDefineAndDraw.h * Author: leixiao * * Created on 2018年1月23日, 上午10:47 */ #ifndef INTERFACEDEFINEANDDRAW_H #define INTERFACEDEFINEANDDRAW_H class Shape { public: virtual void draw()=0; }; #endif /* INTERFACEDEFINEANDDRAW_H */
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include <iostream> #include <string> #include "InterfaceDefineAndDraw.h" using namespace std; class Rectangle:public Shape { public: void draw() { cout << "Inside Rectangle::draw() method."<<endl; return ; } private: }; class Square:public Shape { public : void draw() { cout << "Inside Square::draw() method."<<endl; return ; } }; class Circle:public Shape { public : void draw() { cout << "Inside Circle::draw() method."<<endl; return ; } }; class ShapeFactory { public: Shape* getShape(string type) { if(type == "Rectangle") { Shape *tmp = new Rectangle(); return tmp; } else if(type == "Square") { Shape *tmp = new Square(); return tmp; } else if(type == "Circle") { Shape *tmp = new Circle(); return tmp; } return NULL; } }; int main() { ShapeFactory *shapeFactory = new ShapeFactory(); Shape *shapeRectangle = shapeFactory->getShape("Rectangle"); shapeRectangle->draw(); Shape *shapeSquare = shapeFactory->getShape("Square"); shapeSquare->draw(); Shape *shapeCircle = shapeFactory->getShape("Circle"); shapeCircle->draw(); return 0; }运行结果:
Inside Rectangle::draw() method. Inside Square::draw() method. Inside Circle::draw() method.
github:https://github.com/chujiangke/designpattern