好比说,我有一个界面,查询地理位置,是比较通用的,各个业务,场景都有可能须要用上。可是对于不一样的场景,title的文字可能不同,有些业务但愿进来后展现“选择位置”,有些业务进来后但愿能展现为“发送位置”,还有查询地理位置后,备选的条目数量,以及查询地理位置的范围都有可能根据不一样业务而不同。java
最开始个人作法是这样的。this
class QueryLocationPage { public static final int TYPE_FOR_LOCATION = 1; // 为了定位需求 public static final int TYPE_FOR_SEND_CONV = 2; // 为了发送会话 // 文字显示 private String mTitle = "选择位置"; // 查询范围 private int mSearchRange = 100; // 结果最多显示多少个 private int mMaxResult = 30; // 初始化的时候根据业务的type进行内部行为的配置 private void init(int type) { switch (type) { case TYPE_FOR_LOCATION : mTitle = "选择位置"; mSearchRange = 1000; mMaxResult = 100; break; case TYPE_FOR_SEND_CONV : mTitle = "发送到会话"; mSearchRange = 100; mMaxResult = 30; break; } } }
上述这样的作法其实是很差的,为何我一个纯粹的功能须要知道哪一个业务哪一个业务呢。其实应该是将这些变成配置。code
static class Param { public String title = "选择位置"; public int searchRange = 100; public int maxResult = 30; public Param title(String title) { this.title = title; return this; } public Param searchRange(int sr) { this.searchRange = sr; return this; } public Param maxResult(int mr) { this.maxResult = mr; return this; } } public static final Param SenceForLocation = new Param() .title("选择位置") .searchRange(1000) .maxResult(100); public static final Param SenceForSendConv = new Param() .title("发送到会话") .searchRange(100) .maxResult(30); // 之后扩展的时候,只须要找一个类似的sence(实际上是一个Param),复制一份,改一改你须要的参数,就能够了