构建者设计模式

一、UML

构建者设计模式_第1张图片
Builder.png

二、基本步骤

就一般而言,构建者模式使用内部类的方式来构建对象。主要步骤有:

1、将需要构建的目标类分成多个部件(比如电脑可以分为主机、显示器、键盘、音箱等部件);
2、在目标类内部添加构建类;
3、依次创建部件;
4、将部件组装成目标对象.

三、实现方式

1、定义
/**
 * @author lizihanglove
 * @date 2018/1/8
 * @email [email protected]
 * @desc 构建者模式代码
 */

public class ComputerBuilder {
    private String displayer;
    private String mainUnit;
    private String mouse;
    private String keyboard;

    private ComputerBuilder() {
    }

    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 "ComputerBuilder{" +
                "displayer='" + displayer + '\'' +
                ", mainUnit='" + mainUnit + '\'' +
                ", mouse='" + mouse + '\'' +
                ", keyboard='" + keyboard + '\'' +
                '}';
    }

    public static class Builder{
        private ComputerBuilder target =new ComputerBuilder();

        public Builder installDisplayer(String displayer){
            target.setDisplayer(displayer);
            return this;
        }

        public Builder installMainUnit(String mainUnit){
            target.setMainUnit(mainUnit);
            return this;
        }

        public Builder installMouse(String mouse){
            target.setMouse(mouse);
            return this;
        }

        public Builder installKeybord(String keyboard){
            target.setKeyboard(keyboard);
            return this;
        }

        public ComputerBuilder build(){
            return target;
        }
    }
}
2、调用
 ComputerBuilder.Builder builder = new ComputerBuilder.Builder();
        ComputerBuilder computerBuilder = builder.installDisplayer("显示器")
                .installMainUnit("主机")
                .installMouse("鼠标")
                .installKeybord("键盘")
                .build();
        System.out.println(computerBuilder.toString());
3、结果
ComputerBuilder {displayer='显示器', mainUnit='主机', mouse='鼠标', keyboard='键盘'}

四、说明

构建者模式是很常见的设计模式,根据个人习惯的不同可能实现不一样,但是究其根本,就是将部件依次装配并获得构建目标。

你可能感兴趣的:(构建者设计模式)