Matlab享元模式
程序员文章站
2022-04-14 18:48:01
享元模式(Flyweight)通过共享技术实现相同或相似对象的重用,可以减少创建对象的数量,以减少内存占用和提高性能。Java String的常量池,python logging,线程池,数据库连接池都用到了享元模式。享元模式与单例模式类似,都具有共享变量的特征。本文通过使用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');
上一篇: PHP超全局变量$_SERVER