構建者模式又叫建造者模式(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 (抽象的構造者)ui
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 (指導者,負責調用構造對象的邏輯,控制相應的構造順序)blog
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();