Matlab装饰模式
根据https://www.runoob.com/design-pattern/decorator-pattern.html所给的例子,本人用Matlab语言写了装饰器模式
Shape.m
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。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();
更多精彩

