5、C++设计模式——原型模式(菜鸟教程例子)
原例网址:原型模式(菜鸟教程)
原型模式
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
1 #include <iostream> 2 #include <string> 3 #include <map> 4 using namespace std; 5 6 7 //步骤1 创建一个实现了 Cloneable 接口的抽象类 8 class Shape 9 { 10 public: 11 string getType() 12 { 13 return type; 14 } 15 string getId() 16 { 17 return id; 18 } 19 void setId(string id) 20 { 21 this->id = id; 22 } 23 24 Shape* clone() 25 { 26 return new Shape(*this); 27 } 28 29 protected: 30 string type; 31 private: 32 string id; 33 }; 34 35 36 37 //步骤2 创建扩展了上面抽象类的实体类 38 class Rectangle : public Shape 39 { 40 public: 41 Rectangle() 42 { 43 type = "Rectangle"; 44 } 45 }; 46 47 class Square : public Shape 48 { 49 public: 50 Square() 51 { 52 type = "Square"; 53 } 54 }; 55 56 class Circle : public Shape 57 { 58 public: 59 Circle() 60 { 61 type = "Circle"; 62 } 63 }; 64 65 66 67 //步骤3 创建一个类,获取实体类,并把它们存储在一个 map 中 68 class ShapeCache 69 { 70 public: 71 Shape getShape(string shapeId) 72 { 73 map<string, Shape*>::iterator iter; 74 iter = shapeMap.find(shapeId); 75 return (Shape)*(iter->second)->clone(); 76 } 77 78 void loadCache() 79 { 80 Circle* circle = new Circle; 81 circle->setId("1"); 82 shapeMap.insert( pair<string, Shape*>( circle->getId(), circle ) ); 83 84 Square* square = new Square; 85 square->setId("2"); 86 shapeMap.insert( pair<string, Shape*>( square->getId(), square ) ); 87 88 Rectangle* rectangle = new Rectangle; 89 rectangle->setId("3"); 90 shapeMap.insert( pair<string, Shape*>( rectangle->getId(), rectangle ) ); 91 } 92 93 private: 94 map<string, Shape*> shapeMap; 95 }; 96 97 98 //步骤4 使用 ShapeCache 类来获取存储在 map 中的形状的克隆 99 void main() 100 { 101 ShapeCache shapeCache; 102 shapeCache.loadCache(); 103 104 Shape clonedShape1 = (Shape) shapeCache.getShape("1"); 105 cout << "Shape1 : " << clonedShape1.getType() << endl; 106 107 Shape clonedShape2 = (Shape) shapeCache.getShape("2"); 108 cout << "Shape2 : " << clonedShape2.getType() << endl; 109 110 Shape clonedShape3 = (Shape) shapeCache.getShape("3"); 111 cout << "Shape3 : " << clonedShape3.getType() << endl; 112 113 system("pause"); 114 }
运行结果:


浙公网安备 33010602011771号