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

Matlab建造者模式

程序员文章站 2022-06-24 10:59:20
构建者模式又叫建造者模式(Builder),是将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。创建者模式隐藏了复杂对象的创建过程,它把复杂对象的创建过程加以抽象,通过子类继承或者重载的方式,动态的创建具有复合属性的对象。本文以创建计算机为例,使用Matlab语言来实现。C ......

构建者模式又叫建造者模式(builder),是将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。创建者模式隐藏了复杂对象的创建过程,它把复杂对象的创建过程加以抽象,通过子类继承或者重载的方式,动态的创建具有复合属性的对象。本文以创建计算机为例,使用matlab语言来实现。
computer.m (要构造的复杂对象)

classdef computer < handle
    properties
        name = "";
        cpu = "";
        memory = "";
        disk = "";
    end 
    methods
        function set.name(obj,name)
            obj.name = name;
        end
        function name = get.name(obj)
            name = obj.name;
        end
        function set.cpu(obj,cpu)
            obj.cpu = cpu;
        end
        function cpu = get.cpu(obj)
            cpu = obj.cpu;
        end
        function set.memory(obj,memory)
            obj.memory = memory;
        end
        function memory = get.memory(obj)
            memory = obj.memory;
        end
        function set.disk(obj,disk)
            obj.disk = disk;
        end
        function disk = get.disk(obj)
            disk = obj.disk;
        end
        function showinfo(obj)
            disp("computer:"+obj.name+"{cpu:"+obj.cpu+",memory:"+obj.memory+",disk:"+obj.disk+"}");
        end
    end
end

builder.m (抽象的构造者)

classdef builder < handle
    methods(abstract)
        setname(~,~);
        setcpu(~,~);
        setmemory(~,~);
        setdisk(~,~);
        build(~);
    end
end

concretebuilder.m (具体的构造者)

classdef concretebuilder < builder
    properties
        name = "";
        cpu = "";
        memory = "";
        disk = "";
    end
    methods
        function obj = setname(obj,name)
            obj.name = name;
        end
        function obj = setcpu(obj,cpu)
            obj.cpu = cpu;
        end
        function obj = setmemory(obj,memory)
            obj.memory = memory;
        end
        function obj = setdisk(obj,disk)
            obj.disk = disk;
        end
        function computer = build(obj)
            computer = computer();
            computer.name = obj.name;
            computer.cpu = obj.cpu;
            computer.memory = obj.memory;
            computer.disk = obj.disk;
        end
    end
end

director.m (指导者,负责调用构造对象的逻辑,控制相应的构造顺序)

classdef director
    methods
        function computer = getcomputer(~,builder)
           computer = builder.setname("dell")...
            .setcpu("intel i5")...
            .setmemory("4g")...
            .setdisk("1t")...
            .build();
        end             
    end
end

测试代码:

builder = concretebuilder();
director = director();
computer = director.getcomputer(builder);
computer.showinfo();