比如说,我有一个界面,查询地理位置,是比较通用的,各个业务,场景都有可能需要用上。但是对于不同的场景,title的文字可能不一样,有些业务希望进来后展示“选择位置”,有些业务进来后希望能展示为“发送位置”,还有查询地理位置后,备选的条目数量,以及查询地理位置的范围都有可能根据不同业务而不一样。
最开始我的做法是这样的。
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; } }}
上述这样的做法实际上是不好的,为什么我一个纯粹的功能需要知道哪个业务哪个业务呢。其实应该是将这些变成配置。
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),复制一份,改一改你需要的参数,就可以了