欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Matlab装饰模式

程序员文章站 2022-06-28 11:09:55
根据https://www.runoob.com/design-pattern/decorator-pattern.html所给的例子,本人用Matlab语言写了装饰器模式 Shape.m Circle.m Rectangle.m ShapeDecorator.m RedShapeDecorator ......

根据所给的例子,本人用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();