经常用到Builder,但是很少系统的了解设计模式之建造者模式,是以只知道使用,不明其概念。
为什么要使用建造者模式,先来了解一下Builder设计模式的优点,你就明白了!
解决:可选属性和必填属性无法区分,如果有很多可选参数,我们就必须要写很多个构造函数,这将导致代码的可读性和维护性变差
Builder设计模式:可读性较强,唯一的不足是我们要在PersonBuilder中重复的写一遍Person中的属性。
值得注意的几点: (以Person类为例)
1.Person的构造方法是私有的(protected),也就是说我们不能直接new出Person对象 。
2.我们又将Person的属性用final修饰了,并且在构造方法中都为他们进行了初始化操作,我们只提供了getter方法
3.使用builder模式构造出来的对象有更好的可读性
4.PersonBuilder的属性中只给必须的属性添加final修饰,所以我们必须在PersonBuilder的构造方法中为他们初始化
package com.example.mytry; /** * Created on 2017/11/1. */ public class Person { private final String name; private final int age; private final String address; private final int height; private final int weight; private Person(PersonBuilder personBuilder) { this.name = personBuilder.name; this.age = personBuilder.age; this.address = personBuilder.address; this.height = personBuilder.height; this.weight = personBuilder.weight; } public int getAge() { return age; } public int getHeight() { return height; } public int getWeight() { return weight; } public String getName() { return name; } public String getAddress() { return address; } public static class PersonBuilder { private final String name; private final int age; private String address = ""; private int height = 0; private int weight = 0; public PersonBuilder(String name, int age) { this.name = name; this.age = age; } public PersonBuilder setAddress(String address) { this.address = address; return this; } public PersonBuilder setHeight(int height) { this.height = height; return this; } public PersonBuilder setWeight(int weight) { this.weight = weight; return this; } public Person build() { return new Person(this); } } }
随便定义一个Person类,有name,age,address,height,weight等属性值,在定义一个内部PersonBuilder类,重复写一篇Person类的属性值,必要属性设置为final,可选属性不设置,final修饰的属性创建构造方法,内部类中创建set方法,Person类中创建get方法,所谓final类型,即只能赋值一次。
package com.example.mytry; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Person person = new Person.PersonBuilder("xiaoming", 20).setAddress("东大街18号").setHeight(160).setWeight(90).build(); String address = person.getAddress(); String name = person.getName(); int age = person.getAge(); int height = person.getHeight(); int weight = person.getWeight(); Toast.makeText(this,address+name+age+height+weight,Toast.LENGTH_SHORT).show();}}
到此,一个建造者模式的demo就搞定了,以前难以理解的概念是不是清晰了很多!