Flyweight 享元模式(结构型模式)

介绍

  说到享元模式,第一个想到的应该就是池技术了,数据库连接池、缓冲池等等都是享元模式的应用,所以说享元模式是池技术的重要实现方式。享元模式可以在多个场景中使用一个对象,当然对象中能被放入享元池的都是内部状态的对象,是不随场景变化而变化的元素。而外部状态相反,是不能被共享的元素。

享元模式参与者

  • Flyweight 描述一个接口,通过这个接口可以接收并作用于外部状态
  • ConcreteFlyweight 享元实现类
  • UnsharedConcreteFlyweight 非享元实现类
  • FlyweightFactory 享元工厂类 创建并管理享元实例。

实现代码

class User{//处理的用户
public:
    User(std::string name){
        _name = name;
    }
    std::string GetName(){
        return _name;
    }
private:
    std::string _name;
};

class Flyweight{//享元接口,通过这个接口可以接受并作用域外部状态
public:
    explicit Flyweight(int id):_id(id){}
    void SetName(std::string _name)
    {
        name = _name;
    }
    std::string GetName()
    {
        return name;
    }
    virtual void Work(User *user)
    {

    }
private:
    int _id;
    std::string name;
};

class ConcreteFlyweight: public Flyweight{//具体实现
public:
    explicit ConcreteFlyweight(int id):Flyweight(id){}
    void Work(User *user) override
    {
        std::cout<<"Shared: User:["<GetName()<<"] is doing work ["<GetName()<<"] is doing work ["<SetName(os.str());
            return flyweight;
        }
        return it->second;
    }
    ~FlyweightFactory()
    {
        for(auto x : factory)
        {
            delete x.second;
        }
        factory.clear();
    }
    int size(){
        return static_cast(factory.size());
    }
private:
    std::map factory;
};

int main(){//用户,客户端,可以共享的在享元对象池中,不可以共享的需要客户端自己管理。
    FlyweightFactory factory;
    auto user1 = new User("karl");
    auto user2 = new User("mike");

    auto f1 = factory.getFlyweight(4);
    auto f2 = factory.getFlyweight(4);
    auto f3 = factory.getFlyweight(2);
    f1->Work(user1);
    f2->Work(user1);
    f3->Work(user1);
    f1->Work(user2);
    f2->Work(user2);
    f3->Work(user2);

    std::cout<

输出

创建共享元素4
创建共享元素2
Shared: User:[karl] is doing work [第4号元素]
Shared: User:[karl] is doing work [第4号元素]
Shared: User:[karl] is doing work [第2号元素]
Shared: User:[mike] is doing work [第4号元素]
Shared: User:[mike] is doing work [第4号元素]
Shared: User:[mike] is doing work [第2号元素]
2

特点

  • 节约存储空间

参考

  • 《设计模式:可复用面向对象软件的基础》
  • https://www.cnblogs.com/adamjwh/p/9070107.html

你可能感兴趣的:(Flyweight 享元模式(结构型模式))