本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46489147
创建者模式:将一个复杂对象的构建和其表示分离开来,使得同样的构建过程可以创建出不同的表示。
例如我们需要盖一栋楼房,需要工人来砌墙,需要设计师来设计房子怎么盖,而这里的设计师本身是不干活的,它只是负责下命令让工人干活就行,而真正的创建者是工人,他们最后把楼房盖起来的。所以,最后是向民工要房子而不是向设计师要房子。在这里,房主(客户端)只需要请工人(new Builder())和设计师(new Desinger()),并让设计师指挥工人干活(order2design()),最后房主向工人要房子(getRoom2Clinet())。
详情请见下方代码,希望对你有所帮助。感兴趣可以在我的GitHub上下载源码:https://github.com/pistolove
构建者接口,负责具体构建的事物:
<span style="font-size:14px;">package com.design.builder; //构建者接口,负责构建什么 public interface IBulider { public void makeDoor(); public void makeWindow(); public void makeFloor(); public void makeWall(); public Room getRoom2Clinet(); } </span>
具体的构建者,依据设计进行构建:
<span style="font-size:14px;">package com.design.builder; //工人负责构建房子 public class ConcreateBuilder implements IBulider { private String door = null; private String window = null; private String floor = null; private String wall = null; @Override public void makeDoor() { // TODO Auto-generated method stub System.err.println("start makedoor"); door = "door is ok "; } @Override public void makeWindow() { // TODO Auto-generated method stub System.err.println("start makeWindow"); window = "window is ok "; } @Override public void makeFloor() { // TODO Auto-generated method stub System.err.println("start makeFloor"); floor = "floor is ok "; } @Override public void makeWall() { // TODO Auto-generated method stub System.err.println("start makeWall"); wall = "wall is ok"; } @Override public Room getRoom2Clinet() { if (door != null && window != null && floor != null && wall != null) { return new Room(door, window, floor, wall); } return null; } } </span>
设计师指导工人构建:
<span style="font-size:14px;">package com.design.builder; //设计师知道房子怎么做,但是自己不会做,他指挥工人去做 public class Desinger { private IBulider bulider; public Desinger(IBulider bulider) { this.bulider = bulider; } public void order2design() { bulider.makeDoor(); bulider.makeFloor(); bulider.makeWall(); bulider.makeWindow(); } } </span>
客户端测试:
<span style="font-size:14px;">package com.design.builder; //房主来收房 public class Client { public static void main(String[] args) { IBulider bulider = new ConcreateBuilder(); Desinger desinger = new Desinger(bulider); desinger.order2design(); bulider.getRoom2Clinet(); } } </span>
测试结果:
start makedoor
start makeFloor
start makeWall
start makeWindow
The room is create Ok. It contanins door is ok window is ok floor is ok wall is ok
时间: 2024-12-09 13:45:03