构建者模式又叫建造者模式(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();