欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Matlab观察者模式

程序员文章站 2022-07-10 11:54:32
要点: 1、服务端(Subject)维护一个观察者的列表,以便能够向所有的观察者(Observer)推送信息 2、观察者可以获取服务端的状态 3、服务端和观察者可抽象,可以有多个不同实现 Subject.m ConcreteSubject.m Observer.m ConcreteObserver1 ......

要点:

1、服务端(subject)维护一个观察者的列表,以便能够向所有的观察者(observer)推送信息

2、观察者可以获取服务端的状态

3、服务端和观察者可抽象,可以有多个不同实现

subject.m

classdef subject < handle
    properties(access = private)
        observers = observer.empty();
    end
    methods
        function add(obj,observer)
            obj.observers(end + 1) = observer;
        end
        function rm(obj,observer)
            index = [obj.observers] ~= observer;
            obj.observers = obj.observers(index);
        end
        function notify(obj)
            for i= 1:length(obj.observers)
                obj.observers(i).update(obj);
            end
        end
    end
end

concretesubject.m

classdef concretesubject < subject    
    properties(access = public)
        news
    end   
    methods
        function set.news(obj,news)
            obj.news = news;
        end      
        function news = get.news(obj)
            news = obj.news;
        end
    end
end

observer.m

classdef observer < handle & matlab.mixin.heterogeneous
    methods(abstract)
        update(~,~);
    end
    methods(sealed)   
        function res = eq(obj1,obj2)
            res = eq@handle(obj1,obj2);
        end
        function res = ne(obj1,obj2)
            res = ne@handle(obj1,obj2);
        end
    end 
end

concreteobserver1.m

classdef concreteobserver1 < observer
    properties
        name
    end    
    methods
        function obj = concreteobserver1(name)
            obj.name = name;
        end
        function update(obj,subject)
            disp([obj.name, ' has got subject news: ',subject.news]);
        end
    end
end

concreteobserver2.m

classdef concreteobserver2 < observer
    properties
        name
    end
    methods
        function obj = concreteobserver2(name)
            obj.name = name;
        end
        function update(obj,subject)
            disp([obj.name, ' has received subject news: ',subject.news ]);
        end
    end
end

测试代码:

sub = concretesubject();
sub.news = 'hello matlab';
o1 = concreteobserver1('obs:a');
o2 = concreteobserver2('obs:b');
 
sub.add(o1);
sub.add(o2);
sub.notify();
 
sub.rm(o1);
sub.news = 'hello observer pattern';
sub.notify();