根据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();
结果显示: