设计模式——建造者模式

建造者模式的特点就是

1.如果实体类有多个属性,而在实现实例时不需要将所有属性全部赋值

2.可以按照需要灵活地选择某些属性赋值,就能够得到一个实例

在不使用建造者模式情况下,这个需要的代码量就会很多

 

代码如下:

public class Person {

    private String name = null;
    private int age = -1;
    private String sex = null;
    private String father = null;
    private String mother = null;
    private String husbandOrwife = null;

    private Person(PersonBuilder pb){
        this.name = pb.name;
        this.age = pb.age;
        this.father = pb.father;
        this.mother = pb.mother;
        this.sex = pb.sex;
        this.husbandOrwife = pb.husbandOrwife;
    }

    static class PersonBuilder{
        String name = null;
        int age = -1;
        String sex = null;
        String father = null;
        String mother = null;
        String husbandOrwife = null;

        public PersonBuilder setName(String name){
            this.name = name;
            return this;
        }
        public PersonBuilder setAge(int age){
            this.age = age;
            return this;
        }
        public PersonBuilder setSex(String sex){
            this.sex = sex;
            return this;
        }
        public PersonBuilder setFather(String father){
            this.father = father;
            return this;
        }
        public PersonBuilder setMother(String mother){
            this.mother = mother;
            return this;
        }
        public PersonBuilder setHusbandOrWife(String husbandOrwife){
            this.husbandOrwife = husbandOrwife;
            return this;
        }
        public Person build(){
            return new Person(this);
        }
    }

    @Override
    public String toString(){
        return "[ name="+name+", age="+age+", sex="+sex+", father="+father+", mother="+mother+", husbandOrwife="+husbandOrwife+" ]";
    }
}

 

使用Builder得到实例的代码如下:

    @Test
    public void Test2(){
        Person a = new Person.PersonBuilder().setName("拉拉").setMother("格温").build();
        Person b = new Person.PersonBuilder().setAge(11).setFather("皮特儿").build();
        System.out.println(a); 
}

 

总结:

这个和聚合操作的格式类似,可以调用不同数量,不同种类的方法,最后只要回归到一个终结操作就可以,而这里的终结操作就是build()。

 

建造者模式的关键是,1.构建器是实体类的内部静态类

                                    2.实体类有一个构造器,其参数是构建器(Builder) 

                                    3.通过这个构建器可以将实例的属性赋值。

                                    4.构建器的build()方法,返回的是通过构造器创造的实例

                                    

Constructor(Builder b);

static class Builder{ Constructor build(){
return new Constructor(thisbuilder); }
}

 

                                    

posted @ 2019-03-22 20:35  胡叁安  阅读(324)  评论(0编辑  收藏  举报