要点:
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();
Matlab自带event事件使用的是发布-订阅者模式,与观察者模式类似(区别参考:https://www.cnblogs.com/viaiu/p/9939301.html),代码如下:
classdef EventPublisher < handle events msgRecv end properties name end methods function obj = EventPublisher(name) obj.name = name; end function sendMsg(obj,msg) obj.notify('msgRecv',EventMessage(msg)); end end end
EventSubscriber.m
classdef EventSubscriber < handle properties name end methods function obj = EventSubscriber(name) obj.name = name; end %可以是普通函数、静态函数和成员函数 function dispMsg(obj,src,data) disp("["+data.time+"]"+obj.name + ":"+data.msg+" from "+src.name); end end end
EventMessage.m
classdef EventMessage < event.EventData properties msg time end methods function obj = EventMessage(msg) obj.time = datestr(now); obj.msg = msg; end end end
测试代码
pub = EventPublisher("pub1"); sub = EventSubscriber("sub1"); h = pub.addlistener('msgRecv',@sub.dispMsg); pub.sendMsg("matlab event"); delete(h); pub.sendMsg("matlab event");