设计模式-创建型-建造者模式

1、定义

建造者模式:封装一个复杂对象过程,按照步骤构建对象

写法

1、普通写法

/**
 * 构件
 */
public interface Builder {

    void buildPartA();
    void buildPartB();
    void buildPartC();

}

/**
 * 构件实现
 */
public class ConcreteBuilder implements Builder {

    @Override
    public void buildPartA() {

    }

    @Override
    public void buildPartB() {

    }

    @Override
    public void buildPartC() {

    }
}

/**
 * 建造者
 */
public class Director {

    private Builder builder;

    public  Director(Builder builder) {
        this.builder = builder;
    }

    /**
     * 策略
     */
    public void constructProduct(){
        builder.buildPartA();
        builder.buildPartB();
        builder.buildPartC();
    }

}

public class TestMain {

    public static void main(String[] args) {

        ConcreteBuilder builder = new ConcreteBuilder();
        Director director = new Director( builder );
        director.constructProduct();
    }

}

2、惯用写法,省略构建者

/**
 * 建造者 省略Driector
 * 优点 动态参数配置
 */
public class Request {

    private String body;
    private String head;
    private String parm;

    public void setBody(String body) {
        this.body = body;
    }

    public void setHead(String head) {
        this.head = head;
    }

    public void setParm(String parm) {
        this.parm = parm;
    }

    /**
     *
     */
    public static class Builder{

        private String body;
        private String head;
        private String parm;

        public Builder setBody(String body) {
            this.body = body;
            return this;
        }

        public Builder setHead(String head) {
            this.head = head;
            return this;
        }

        public Builder setParm(String parm) {
            this.parm = parm;
            return this;
        }

        public Request create(){
            Request request = new Request();
            request.setHead( head );
            request.setParm( parm );
            request.setBody( body );
            return request;
        }
    }
}

public class TestMain {

    public static void main(String[] args) {
        Request request = new Request.Builder()
                .setHead( "head" )
                .setParm( "parm" )
                .setBody( "body" )
                .create();
    }

}

代码示例

https://github.com/yinlingchaoliu/23-design-pattern

你可能感兴趣的:(设计模式-创建型-建造者模式)