一、在上一篇博客中,我大概写出了建造者设计模式的简单逻辑,但是在上一篇的代码里面还是有设计不好的地方,就是客户端建造一个房子,要提供给客户端的信息量太多了,不仅要知道具体的工人,还要知道具体的建造公司。所以就不符合java最少知道原则的设计理念。接下来的代码我会在原有的基础上,再次重构,简化生成新的建造者模型出来。
二、新建新的包noddesigner,只保留原有的WorkBuilder\Room两个类:
三、将Room类中的set、get方法全部剔除掉,并在workbuilder类中创建一个副本(内部类RoomParams):
public class Room { private String window; private String floor; public void apply(WorkBuilder.RoomParams params) { window = params.window; floor = params.floor; } @Override public String toString() { return "Room{" + "window='" + window + '\'' + ", floor='" + floor + '\'' + '}'; } }
四、 WrokBuilder类的改进为:
public class WorkBuilder { public RoomParams params; public WorkBuilder() { this.params = new RoomParams(); } public WorkBuilder makeWindow(String window) { params.window = window; return this; } public WorkBuilder makeFloor(String floor) { params.floor = floor; return this; } public Room build() { Room room = new Room(); room.apply(params); return room; } public class RoomParams{ public String window; public String floor; } }
五、最后看看真正客户端的调用代码:
public class Client { @Test public void test() { Room room = new WorkBuilder() .makeWindow("fashi").makeFloor("oushi").build(); System.out.print(room); } }
写到这里,大家可以清楚的看到Room房子的产生只保留了WorkBuilder这个类的调用,并且我们可以随意设置里面的参数,而不影响我们的代码结构。
代码下载地址:https://github.com/cWX411904/Builder