Builder模式

2016-11-28  本文已影响10人  helloKai

Builder模式:

父类:

public class Computer {
    protected String mBoard;
    protected String mDisplay;
    protected String mOs;

    protected Computer() {
    }
}

具体实现类:

public class Macbook extends Computer {
    private Macbook(Builder builder) {
        this.mOs = builder.mOs;
        this.mBoard = builder.mBoard;
        this.mDisplay = builder.mDisplay;
    }

    static class Builder {
        protected String mBoard;
        protected String mDisplay;
        protected String mOs;

        public Builder setmOs(String mOs) {
            this.mOs = mOs;
            return this;
        }

        public Builder setmBoard(String mBoard) {
            this.mBoard = mBoard;
            return this;
        }

        public Builder setmDisplay(String mDisplay) {
            this.mDisplay = mDisplay;
            return this;
        }

        public Macbook build() {
            return new Macbook(this);
        }
    }
}

具体调用代码:

Macbook macbook = new Macbook.Builder()
.setmBoard("board")
.setmDisplay("display")
.setmOs("os")
.build();
上一篇下一篇

猜你喜欢

热点阅读