模式(Proxy)"/>
Matlab代理模式(Proxy)
代理模式(Proxy)就是给一个对象提供一个代理对象,并有代理对象来控制对原有对象的引用。代理模式和装饰模式非常类似,但最主要的区别是代理模式中,代理类对被代理的对象有控制权,决定其执行或者不执行。本文根据.html给出的结构图,使用Matlab语言实现代理代理模式。
Subject.m
classdef Subjectmethods(Abstract)request(~);end
end
RealSubject.m
classdef RealSubject < Subject methodsfunction request(obj)mc = metaclass(obj);disp(mc.Name + ":request");endend
end
Proxy.m
classdef Proxy < Subjectpropertiessubendmethodsfunction obj = Proxy(sub)obj.sub = sub;endfunction request(obj)if(randi([0,1]))obj.before();obj.sub.request();obj.after();elsemc = metaclass(obj);disp(mc.Name + ":no request");endendfunction before(obj)mc = metaclass(obj);disp(mc.Name + ":start request");endfunction after(obj)mc = metaclass(obj);disp(mc.Name + ":end request");endend
end
测试代码:
a = RealSubject();
a.request();b = Proxy(a);
b.request();
结果:
更多推荐
Matlab代理模式(Proxy)
发布评论