今天小编来说一下Android中的一种设计模式--建造者模式Builder
那么对于Android初级来说,Builder设计模式可能在我们开发中用过的很少,但是我们可能见过,我们经常用的AlterDialog.Builder就是一种建造者模式。那么到底什么是建造者模式呢?下面我们来看看它的标准定义:
package com; /** * Created by Hankkin on 15/10/21. */ public class ImageBean { private int id; //图片id private String path; //图片路径 private long size; //图片大小 private String type; //图片类型 public ImageBean() { } public ImageBean(int id, String path, long size, String type) { this.id = id; this.path = path; this.size = size; this.type = type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public String getType() { return type; } public void setType(String type) { this.type = type; } }我们定义了一个ImageBean实体,里面包含id、path、size、type属性,其中还包含空的构造方法和一个包含参数的构造。这样我们在声明这个实体的时候可以给这个实体赋值。
package com; /** * Created by Hankkin on 15/10/21. */ public class ImageBean { private int id; //图片id private String path; //图片路径 private long size; //图片大小 private String type; //图片类型 public ImageBean() { } public ImageBean(Builder builder) { this.id = builder.id; this.path = builder.path; this.size = builder.size; this.type = builder.type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public String getType() { return type; } public void setType(String type) { this.type = type; } public static class Builder{ private int id; private String path; private long size; private String type; public Builder id(int id){ this.id = id; return this; } public Builder path(String path){ this.path = path; return this; } public Builder size(long size){ this.size = size; return this; } public Builder type(String type){ this.type = type; return this; } public ImageBean build(){ return new ImageBean(this); } } }
ImageBean.Builder builder = new ImageBean.Builder(); ImageBean ib = builder.id(11).path("xxx").size(1111).type("jpg").build();
在以下情况使用Build模式:
1 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
2 当构造过程必须允许被构造的对象有不同的表示时。
3 Builder模式要解决的也正是这样的问题:
当我们要创建的对象很复杂的时候(通常是由很多其他的对象组合而成),
我们要复杂对象的创建过程和这个对象的表示(展示)分离开来,
这样做的好处就是通过一步步的进行复杂对象的构建,
由于在每一步的构造过程中可以引入参数,使得经过相同的步骤创建最后得到的对象的展示不一样。