代理模式(Proxy)就是給一個對象提供一個代理對象,並有代理對象來控制對原有對象的引用。代理模式和裝飾模式很是相似,但最主要的區別是代理模式中,代理類對被代理的對象有控制權,決定其執行或者不執行。本文根據https://www.cnblogs.com/gonjan-blog/p/6685611.html給出的結構圖,使用Matlab語言實現代理代理模式。
html
Subject.m代理
classdef Subject methods(Abstract) request(~); end end
RealSubject.mhtm
classdef RealSubject < Subject methods function request(obj) mc = metaclass(obj); disp(mc.Name + ":request"); end end end
Proxy.m對象
classdef Proxy < Subject properties sub end methods function obj = Proxy(sub) obj.sub = sub; end function request(obj) if(randi([0,1])) obj.before(); obj.sub.request(); obj.after(); else mc = metaclass(obj); disp(mc.Name + ":no request"); end end function before(obj) mc = metaclass(obj); disp(mc.Name + ":start request"); end function after(obj) mc = metaclass(obj); disp(mc.Name + ":end request"); end end end
test.mblog
a = RealSubject(); a.request(); b = Proxy(a); b.request();