美文网首页设计模式
Builder设计模式——化妆师

Builder设计模式——化妆师

作者: 0ur | 来源:发表于2018-11-28 23:09 被阅读0次

    菜鸟正在努力学习中,如有出入,往大佬扶正,谢谢!!!

    将一个复杂的对象的构建和它的表示分开,使得同样的构建过程可以创建不同的表示
    cover

    左图经过一系列的手法变成了右图,反正我喜欢右图,废话不多说,看代码

    /**
     * 美女类
     */
    public class Belle {
    
        //隔离霜
        private String mSunScreen;
        //粉底
        private String mFoundation;
        //眼影
        private String EyeShadows;
        //口红
        private String mLmipstick;
    
        public Belle(Builder builder) {
            this.mSunScreen = builder.mSunScreen;
            this.mFoundation = builder.mFoundation;
            this.EyeShadows = builder.mEyeShadows;
            this.mLmipstick = builder.mLmipstick;
    
        }
    
        @Override
        public String toString() {
            return "Belle{" +
                    "mSunScreen='" + mSunScreen + '\'' +
                    ", mFoundation='" + mFoundation + '\'' +
                    ", EyeShadows='" + EyeShadows + '\'' +
                    ", mLmipstick='" + mLmipstick + '\'' +
                    '}';
        }
    
        public static class Builder {
    
            private String mSunScreen = "SunScreen";
            private String mFoundation = "Foundation";
            private String mEyeShadows = "EyeShadows";
            private String mLmipstick = "Lmipstick";
    
            public Builder() {
            }
    
            /**
             * 隔离霜
             *
             * @param sunScreen
             */
            public Builder setSunScreen(String sunScreen) {
                this.mSunScreen = sunScreen;
                return this;
            }
    
    
            /***
             * 设置粉底
             * @param foundation
             */
            public Builder setFoundation(String foundation) {
                this.mFoundation = foundation;
                return this;
            }
    
    
            /**
             * 设置眼影
             *
             * @param eyeshadows
             */
            public Builder setEyeShadows(String eyeshadows) {
                this.mEyeShadows = eyeshadows;
                return this;
            }
    
    
            /**
             * 设置口红
             *
             * @param lmipstick
             */
            public Builder setLmipstick(String lmipstick) {
                this.mLmipstick = lmipstick;
                return this;
            }
    
    
            public Belle build() {
                return new Belle(this);
            }
    
        }
    }
    
    

    关键:在于set 返回的是当前的对象(this 链条式的基础)。
    优点:将配置从目标类隔离出来,避免了过多的setter()方法,容易扩展。
    缺点:会产生多余的Builder对象。

    大佬,冲我的图,点个赞再走~~~

    相关文章

      网友评论

        本文标题:Builder设计模式——化妆师

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