设计模式读书笔记(三)Builder 模式

2017-11-19  本文已影响7人  learner222

1. Builder 模式的简单实现(书中例子)

public abstract class Computer {

    protected String mBoard;

    protected String mDisplay;

    protected String mOS;

    protected Computer() {

    }

    public void setBoard(String board) {
        mBoard = board;
    }

    public void setDisplay(String display) {
        mDisplay = display;
    }

    public abstract void setOS();
}
public class Macbook extends Computer {

    protected Macbook() {

    }

    @Override
    public void setOS() {
        mOS = "Mac OS X";
    }
}
public abstract class Builder {

    public abstract void buildBoard(String board);

    public abstract void buildDisplay(String display);

    public abstract void buildOS();

    public abstract Computer create();
}
public class MacbookBuilder extends Builder {

    private Computer mComputer = new Macbook();

    @Override
    public void buildBoard(String board) {
        mComputer.setBoard(board);
    }

    @Override
    public void buildDisplay(String display) {
        mComputer.setDisplay(display);
    }

    @Override
    public void buildOS() {
        mComputer.setOS();
    }

    @Override
    public Computer create() {
        return mComputer;
    }
}
public class Director {

    Builder mBuilder;

    public Director(Builder builder) {
        mBuilder = builder;
    }

    public void construct(String board, String display) {
        mBuilder.buildBoard(board);
        mBuilder.buildDisplay(display);
        mBuilder.buildOS();
    }
}

书中给出的 Builder 模式实现,最终通过调用 Director 对象的 construct() 方法来构建 Computer,在学习工作中,我们经常能看到 Builder 模式的另一种实现模式,直接通过链式调用 Builder 对象来构建。下面以 OkHttp 中的 Request Builder 举例,来看看他是怎么实现 Builder 模式的。

public static class Builder {
    HttpUrl url;
    String method;
    Headers.Builder headers;
    RequestBody body;
    Object tag;

    public Builder() {
        this.method = "GET";
        this.headers = new Headers.Builder();
    }

    Builder(Request request) {
        this.url = request.url;
        this.method = request.method;
        this.body = request.body;
        this.tag = request.tag;
        this.headers = request.headers.newBuilder();
    }

    // Builder 的 set 方法,都会返回 Builder 自己,这样就可以链式调用
    public Builder url(HttpUrl url) {
        if (url == null) throw new NullPointerException("url == null");
        this.url = url;
        return this;
    }

    // ……
    
    // 最后构建的时候,将 Builder 对象自身作为 Request 构造方法参数传入,Request 通过提取 Builder 对象中的属性,来构建自身
    public Request build() {
        if (url == null) throw new IllegalStateException("url == null");
        return new Request(this);
    }
}
上一篇下一篇

猜你喜欢

热点阅读