要點: 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();