Matlab组合模式
组合模式(Composite),将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。组合模式的目的是让客户端不再区分操作的是组合对象(Composite)还是叶子对象(Leaf),而是以一个统一的方式来操作。实现这个目标的关键之处,是设计一个抽象的组件类,让它可以代表组合对象和叶子对象。这样一来,客户端就不用区分到底是组合对象还是叶子对象了,只需要全部当成组件对象进行统一的操作就可以了。计算机系统的文件夹相当于组合模式的Composite,文件相当于组合模式的Leaf。本文按照下面的类图,用Matlab代码实现组合模式。
Component.m
classdef Component < handle & matlab.mixin.Heterogeneous properties(Access = protected) name end methods function obj = Component(name) obj.name = name; end end methods(Abstract) Add(~,~); Remove(~,~); Display(~,~); 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
Composite.m
classdef Composite < Component properties(Access = private) children = Component.empty(); end methods function obj = Composite(name) obj = obj@Component(name); end function Add(obj,c) obj.children(end + 1)=c; end function Remove(obj,c) index = [obj.children] ~= c; obj.children = obj.children(index); end function Display(obj,depth) temp = ""; for i = 1:depth temp = temp + "-"; end disp(temp + obj.name); for i = 1:length(obj.children) obj.children(i).Display(depth + 1); end end end end
Leaf.m
classdef Leaf < Component methods function obj = Leaf(name) obj = obj@Component(name); end function Add(~,~) end function Remove(~,~) end function Display(obj,depth) temp = ""; for i = 1:depth temp = temp + "-"; end disp(temp + obj.name); end end end
测试代码
root = Composite("Composite root"); compX = Composite("Composite X"); root.Add(Leaf("Leaf A")); root.Add(compX); root.Add(Leaf("Leaf B")); compX.Add(Leaf("Leaf XA")); compX.Add(Leaf("Leaf XB")); compXY = Composite("Composite XY"); compX.Add(compXY); leafXYA = Leaf("Leaf XYA"); compXY.Add(leafXYA); compXY.Add(Leaf("Leaf XYB")); compXY.Remove(leafXYA); root.Display(0);
赞 (0)