享元(FlyWeight)模式

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。

 代码:

#include <iostream>
#include <string>
#include <ctime>
#include <map>
using namespace std;

class Shape
{
public:
    virtual void draw() = 0;
    virtual ~Shape(){}
};

class Circle : public Shape
{
public:
    Circle(string color, int x=0, int  y=0, int radius=0) :_color(color), _x(x), _y(y), _radius(radius){}

    void setX(int x)
    { 
        _x = x;
    }

    void setY(int y)
    {
        _y = y;
    }

    void setRadius(int radius)
    {
        _radius = radius;
    }

    void set(int x, int y)
    {
        _x = x;
        _y = y;
    }

    virtual void draw()
    {
        cout << "Draw circle [color:" <<  _color << ", at(" <<  _x<< ","<<  _y << "), radius("<< _radius << ")]" << endl;
    }

private:
    int _x;
    int _y;
    int _radius;
    string _color; //内部状态
};

class CircleFactory
{
public:
    CircleFactory()
    {
        _map.clear();
    }

    Circle *getCircle(string color)
    {
        if (_map.find(color) == _map.end())
        {
            int x, y;
            x = getRandomXY();
            y = getRandomXY();
            Circle *c = new Circle(color, x, y);
            c->setRadius(100);
            _map[color] = c;
            return c;
        }
        return _map[color];
    }

    ~CircleFactory()
    {
        for (auto it = _map.begin(); it != _map.end(); ++it)
        {
            delete it->second;
        }
    }

    int getRandomXY()
    {
        return rand() % 100;
    }
    
    int getCricleCount()
    {
        return _map.size();
    }
    
    string getRandomColor()
    {
        static string colors[] = { "red", "Green", "blue", "white", "black", "purple", "yellow", "orange"};
        static int len = sizeof(colors) / sizeof(*colors);
        int index = rand() % len;
        return colors[index];
    }
    
private:
    map<string, Circle*> _map;
};



void test()
{    
    srand(time(NULL));
    CircleFactory cf;
    Circle *c = NULL;

    for (int i = 0; i < 10; ++i)
    {
        string color = cf.getRandomColor();
        c = cf.getCircle(color);
        c->draw();

    }
}

int main()
{    
    test();
    cin.get();
    return 0;
}

 效果:

原文地址:https://www.cnblogs.com/hupeng1234/p/6798289.html