根據https://www.runoob.com/design-pattern/decorator-pattern.html所給的例子,本人用Matlab語言寫了裝飾器模式 Shape.m Circle.m Rectangle.m ShapeDecorator.m RedShapeDecorator ...
根據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();