zoukankan      html  css  js  c++  java
  • [设计模式]<5>. C++与享元模式(flyweight pattern)

    默默的EEer

    原文地址:

    http://www.cnblogs.com/hebaichuanyeah/p/5616427.html

    享元模式指“运用共享技术有效地支持大量细粒度的对象”。

    java中的string对象就是利用的享元模式,不同的string对象相同的字符串,则实质指向的字符串地址是一样的。(事实上java里面的事件机制就是所谓观察者模式)

    一个极其简单的例子

    #include <iostream>
    #include <map>
    
    using namespace std;
    
    class Flyweight
    {
    protected:
        string name;
    public:
        Flyweight(){}
        virtual ~Flyweight(){}
        virtual void Operation()
        {
    
        }
    };
    
    class someObject: public Flyweight
    {
    
    public:
        someObject(string str)
        {
            cout<<"创建一个"<<name<<"对象"<<endl;
            name = str;
        }
        virtual void Operation()
        {
            cout<<name<<"对象操作"<<endl;
        }
    
    };
    class FlyweightFactory
    {
        //
    private:
        map<string,Flyweight *>  flyweightMap;
        Flyweight * ret;
    public:
        Flyweight * getFlyweight(string name)
        {
            if(flyweightMap.count(name))
                ret =flyweightMap[name];
            else
            {
                ret = new someObject(name);
                flyweightMap.insert(pair<string,Flyweight *>(name, ret));
            }
            return ret;
        }
    };
    
    main()
    {
        FlyweightFactory flyweightFactory;
        Flyweight * test = flyweightFactory.getFlyweight("test");
    }
    
  • 相关阅读:
    判断当前时间为星期几
    springboot+mysql数据源切换
    表单上传图片
    po,vo,bo,dto,dao解释
    生成电脑的SSH key
    单例模式
    事物的特性和隔离级别
    springAOP自定义注解讲解
    Spring依赖注入(DI)的三种方式
    redis持久化
  • 原文地址:https://www.cnblogs.com/hebaichuanyeah/p/5616427.html
Copyright © 2011-2022 走看看