zoukankan      html  css  js  c++  java
  • Matlab享元模式

    享元模式(Flyweight)通过共享技术实现相同或相似对象的重用,可以减少创建对象的数量,以减少内存占用和提高性能。Java String的常量池,python logging,线程池,数据库连接池都用到了享元模式。享元模式与单例模式类似,都具有共享变量的特征。本文通过使用matlab语言对享元模式进行实现。

     IFlyweight.m

    classdef IFlyweight < handle
        methods(Abstract)
            print(~);
        end
    end

    Flyweight.m

    classdef Flyweight < IFlyweight
        properties
            color
        end   
        methods
            function obj = Flyweight(color)
                obj.color =  color;
            end
            function print(obj)
                disp("color:"+obj.color)
            end
        end
    end
    

    FlyweightFactory.m

    classdef FlyweightFactory < handle    
        methods(Static)
            function res = getFlyweightMap()
                persistent flyweightMap;
                if isempty(flyweightMap) || ~isvalid(flyweightMap)
                    flyweightMap = containers.Map();
                end
                res = flyweightMap;
            end
            function obj = getFlyweight(color)
                flyweightMap = FlyweightFactory.getFlyweightMap();
                if(~flyweightMap.isKey(color))
                    flyweightMap(color) = Flyweight(color);
                end
                obj = flyweightMap(color);
            end
            function size = getFlyweightMapSize()
                flyweightMap = FlyweightFactory.getFlyweightMap();
                size = flyweightMap.length();
            end
        end
    end

    测试代码

    fw1 = FlyweightFactory.getFlyweight('Red');
    fw2 = FlyweightFactory.getFlyweight('Blue');
    fw3 = FlyweightFactory.getFlyweight('Red');
    fw1.print();
    fw2.print();
    fw3.print();
    disp(FlyweightFactory.getFlyweightMapSize());
    clear('FlyweightFactory');
  • 相关阅读:
    转:C/C++基本数据类型所占字节数
    转:为什么C++中空类和空结构体大小为1?
    转:内存字节对齐
    转:100层楼扔两个鸡蛋的问题
    移动互联网
    辗转相除法
    斐波那契数列
    error C2783: 无法为“T”推导 模板 参数
    创新工场和海豚浏览器宣讲会启示
    转:快速排序的一个小问题没想明白,求助各位
  • 原文地址:https://www.cnblogs.com/usaddew/p/10947139.html
Copyright © 2011-2022 走看看