Matlab代理模式(Proxy)

 

代理模式(Proxy)就是給一個對象提供一個代理對象,並有代理對象來控制對原有對象的引用。代理模式和裝飾模式非常類似,但最主要的區別是代理模式中,代理類對被代理的對象有控制權,決定其執行或者不執行。本文根據https://www.cnblogs.com/gonjan-blog/p/6685611.html給出的結構圖,使用Matlab語言實現代理代理模式。

Subject.m

classdef Subject
    methods(Abstract)
        request(~);
    end
end

RealSubject.m

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

測試代碼:

a = RealSubject();
a.request();

b = Proxy(a);
b.request();

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章