构建者模式
Builder构建者模式:“将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。”
它属于创建类模式,一般来说,如果一个对象的构建比较复杂,超出了构造函数所能包含的范围,就可以使用工厂模式和Builder模式,相对于工厂模式会产出一个完整的产品,Builder应用于更加复杂的对象的构建,甚至只会构建产品的一个部分,直白来说,就是使用多个简单的对象一步一步构建一个复杂的对象。
比如我们要组装一台电脑,既要生产显示器,又要生产鼠标,键盘,这时候我们就用到构建者模式。
Computer类:
package designpattern.constructor;
/**
* @author liuyj
* @Title: Computer
* @create 2020-06-10 17:21
* @ProjectName demo-designpattern
* @Description: TODO
*/
public class Computer {
//显示器
private String displayer;
//主机
private String mainUnit;
//鼠标
private String mouse;
//键盘
private String keyboard;
public String getDisplayer() {
return displayer;
}
public void setDisplayer(String displayer) {
this.displayer = displayer;
}
public String getMainUnit() {
return mainUnit;
}
public void setMainUnit(String mainUnit) {
this.mainUnit = mainUnit;
}
public String getMouse() {
return mouse;
}
public void setMouse(String mouse) {
this.mouse = mouse;
}
public String getKeyboard() {
return keyboard;
}
public void setKeyboard(String keyboard) {
this.keyboard = keyboard;
}
@Override
public String toString() {
return "Computer{" +
"displayer='" + displayer + '\'' +
", mainUnit='" + mainUnit + '\'' +
", mouse='" + mouse + '\'' +
", keyboard='" + keyboard + '\'' +
'}';
}
}
构建者类:
package designpattern.constructor;
/**
* @author liuyj
* @Title: ComputerBuilder
* @create 2020-06-10 17:25
* @ProjectName demo-designpattern
* @Description: 构建者类
*/
public class ComputerBuilder {
private Computer computer=new Computer();
public void installDisplayer(String displayer){
computer.setDisplayer(displayer);
}
public void installMainUnit(String mainUnit){
computer.setMainUnit(mainUnit);
}
public void installMouse(String mouse){
computer.setMouse(mouse);
}
public void installKeyBoard(String keyboard){
computer.setKeyboard(keyboard);
}
public Computer getComputer() {
return computer;
}
}
测试类:
package designpattern.constructor;
/**
* @author liuyj
* @Title: ConstructorTest
* @create 2020-06-10 17:33
* @ProjectName demo-designpattern
* @Description: 测试类
*/
public class ConstructorTest {
public static void main(String[] args) {
ComputerBuilder computerBuilder=new ComputerBuilder();
computerBuilder.installDisplayer("显示器");
computerBuilder.installMainUnit("主机");
computerBuilder.installKeyBoard("键盘");
computerBuilder.installMouse("鼠标");
Computer computer=computerBuilder.getComputer();
System.out.println(computer);
}
}
代码实例:
设计模式demo