美文网首页
Builder模式

Builder模式

作者: helloKai | 来源:发表于2016-11-28 23:52 被阅读10次

    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();
    

    相关文章

      网友评论

          本文标题:Builder模式

          本文链接:https://www.haomeiwen.com/subject/rkcapttx.html