Android开发

Builder建造者模式

2017-09-18  本文已影响36人  johnnycmj

建造者模式

1 定义

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

builder.png

2通用代码

public class Product {
    public void doSomething(){

    }
}
public abstract class Builder {

    //设置产品的不同部分,以获得不同的产品
    protected abstract void builderPart1();

    protected abstract void builderPart2();

    //建造产品
    public abstract Product getProduct();
}
public class ConcreateBuilder extends Builder {

    private Product product = new Product();

    @Override
    protected void builderPart1() {

    }

    @Override
    protected void builderPart2() {

    }

    @Override
    public Product getProduct() {
        return product;
    }
}
public class Director {
    private Builder builder = new ConcreateBuilder();

    public Product getProductA(){
        builder.builderPart1();
        builder.builderPart2();

        return builder.getProduct();
    }
}

3适用场景

4 特点

在现实开发过程,Director这个角色经常会被省略。而直接使用一个Builder来进行对象的组装,这个Builder通常为链式调用,它的关键是每个set方法都返回自身,即return this,这样setter就可以链式调用。

new Builder().setA("A").setB("B").setC("C").create();

5 优点

6 缺点

会产生多于的Builder对象以及Director对象,消耗内存。

7 链式调用Builder模式

CustomerDialog.java

public class CustomerDialog {

    private String title;
    private String message;
    private String button;

    public void setTitle(String title){
        this.title  = title;
    }

    public void setMessage(String message){
        this.message = message;
    }

    public void setButton(String button){
        this.button = button;
    }

    @Override
    public String toString() {
        return "This dialog is [ title="+title+" , message="+message+" , button="+button+"]";
    }

    public String show(){
        return this.toString();
    }
}

DialogBuilder.java

public class DialogBuilder {

    private CustomerDialog dialog;


    public DialogBuilder(){
        dialog = new CustomerDialog();
    }

    public DialogBuilder setTitle(String title){
        dialog.setTitle(title);
        return this;
    }

    public DialogBuilder setMessage(String message) {
        dialog.setMessage(message);
        return this;
    }

    public DialogBuilder setButton(String button) {
        dialog.setButton(button);
        return this;
    }

    public CustomerDialog create(){
        return dialog;
    }
}

DisplayDialog.java

public class DisplayDialog {

    public static DialogBuilder with(){
        return new DialogBuilder();
    }
}
@Test
public void testMain1(){
    CustomerDialog dialog =
            DisplayDialog.with()
            .setTitle("Dialog test")
            .setMessage("Dialog content")
            .setButton("Dialog button")
            .create();

    System.out.println(dialog.show());

}
上一篇下一篇

猜你喜欢

热点阅读