Chinaunix首页 | 论坛 | 博客
  • 博客访问: 164726
  • 博文数量: 60
  • 博客积分: 15
  • 博客等级: 民兵
  • 技术积分: 638
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-26 10:59
个人简介

喜欢coding,因为那是一件伟大的事情,是将无生命的IC赋予灵魂的过程,让我拥有了和上帝一样的成就感。(w1c2g3@163.com)

文章分类

全部博文(60)

文章存档

2017年(7)

2016年(41)

2015年(1)

2014年(4)

2013年(7)

我的朋友

分类: C/C++

2016-10-30 23:14:09

蝇量模式(享元模式) (flyweight)如想让某个类的一个实例能用来提供许多“虚拟实例”,就使用蝇量模式。




  1. #include <iostream>
  2. #include <map>
  3. #include <stdlib.h>

  4. using namespace std;


  5. struct Circle {
  6. public:
  7.     Circle(string color) {
  8.         this->color = color;
  9.     }
  10.     void setX(int x) {
  11.         this->x = x;
  12.     }
  13.     void setY(int y) {
  14.         this->y = y;
  15.     }
  16.     void setRadius(int radius) {
  17.         this->radius = radius;
  18.     }
  19.     void draw() {
  20.         cout << "Circle: Draw() [Color : " << color <<
  21.          ", x : " << x << ", y : " << y <<
  22.          ", radius : " << radius << endl;
  23.     }
  24. private:
  25.     string color;
  26.     int x;
  27.     int y;
  28.     int radius;
  29. };

  30. struct CircleFactory {
  31. public:
  32.     Circle *getCircle(string color) {
  33.         Circle *circle;
  34.         map<string, Circle *>::iterator it = circleMap.find(color);

  35.         if (it == circleMap.end()) {
  36.             circle = new Circle(color);
  37.             circleMap.insert(pair<string, Circle *>(color, circle));
  38.             cout << "Creating circle of color : " << color << endl;
  39.         } else {
  40.             circle = it->second;
  41.         }
  42.         return circle;
  43.     }
  44. private:
  45.     map<string, Circle *> circleMap;
  46. };

  47. string colors[] = {"Red", "Green", "Blue", "White", "Black"};

  48. string getRandomColor() {
  49.     return colors[rand() % (sizeof(colors)/sizeof(colors[0]))];
  50. }

  51. int getRandomX() {
  52.     return rand();
  53. }

  54. int getRandomY() {
  55.     return rand();
  56. }

  57. int main(int argc, char **argv) {
  58.     CircleFactory *circleFactory = new CircleFactory();

  59.     for(int i=0; i < 20; ++i) {
  60.         Circle *circle = (Circle *)circleFactory->getCircle(getRandomColor());
  61.         circle->setX(getRandomX());
  62.         circle->setY(getRandomY());
  63.         circle->setRadius(100);
  64.         circle->draw();
  65.     }
  66. }

阅读(872) | 评论(0) | 转发(0) |
0

上一篇:责任链模式

下一篇:解释器模式

给主人留下些什么吧!~~