Matlab装饰模式
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。根据https://www.runoob.com/design-pattern/decorator-pattern.html所给的例子,本人用Matlab语言写了装饰器模式
Shape.m
classdef Shape < handle methods(Abstract) draw(obj); end end
Circle.m
classdef Circle < Shape methods function draw(~) disp('Shape: Circle'); end end end
Rectangle.m
classdef Rectangle < Shape methods function draw(~) disp('Shape: Rectangle') end end end
ShapeDecorator.m
classdef ShapeDecorator < Shape properties shape end methods function obj = ShapeDecorator(shape) obj.shape=shape; end function draw(obj) obj.shape.draw(); end end end
RedShapeDecorator.m
classdef RedShapeDecorator < ShapeDecorator methods function obj = RedShapeDecorator(shape) obj = obj@ShapeDecorator(shape); end function draw(obj) draw@ShapeDecorator(obj); disp('Border Color:Red'); end end end
测试代码:
circle = Circle(); redCircle =RedShapeDecorator(Circle()); redRectangle = RedShapeDecorator(Rectangle()); disp('Circle with normal border'); circle.draw(); disp('Circle of red border'); redCircle.draw(); disp('Rectangle of red border'); redRectangle.draw();