设计模式之Builder模式总结

大家在没有接触builder模式之前,写一个类会这样写

class A{

    private String a;

    private String b;

    private String c;




    public A(String a, String b, String c){}  

} 

然后这么使用①

new A("a", "b", "c"); 

或者这么使用②

A a = new A();

a.setA("a");

a.setB("b");

...

但是这么使用你有没有发现一个问题,①你真的记得住各种参数的顺序?别说顺序了,你真的记得住各种参数?是不是也要每次翻开这个类来查看?如果这个类是你自己写的还好,一眼就看明白了,如果这个类是别人写的呢?难免会发生不必要的错误,②如果使用第二种方式,这样方式,使得该类的其他属性在被创建之后被修改,给程序带来了一些不安全性,特别是多线程中。特别是我举例的还是比较简单的类,不复杂的,如果有些类很复杂,那真的就会很难受了。
所以这个时候builder模式就闪亮登场了!解救你于水深火热之中

class A{

    private String a;

    private String b;

    private String c;

   public static class Builder {

    private String a;

    private String b;

    private String c;

        public Builder setValueA(String a) {
            this.a = a;
            return this;
        }

        public Builder setValueB(String b) {
            this.b = b;
            return this;
        }

        public Builder setValueC(String c) {
            this.c = c;
            return this;
        }

        void apply(A A){
            A.a=this.a;
            A.b=this.b;
            A.c=this.c;
        }  
        public A build() {
            A test =new A();
            apply(test);
            return test;
        }

    }

} 

然后这么调用

A a = new A.Buider()
.setValueA("I am A")
.setValueB("I am B")
.setValueC("I am C")
.build();

这一串的链式调用是不是很舒服,当你buider()然后点的时候,编译器就会提示里面的函数了,是不是对参数一目了然了,再也不会担心忘记参数了。

总结

使用builder模式显著带来的好处就是有良好的封装性,可以让客户端不必知道内部组成的细节,链式调用各种参数即可,而且建造与表示分离,容易扩展,当然也要认识到这种模式会产生多余的builder对象消耗内存,而且还会让程序员多敲不少代码(这点可忽略 哈哈哈哈)!

猜你喜欢

转载自blog.csdn.net/hjsir/article/details/80257500