Android中设计模式--策略模式(封装会变化的算法部分,面向接口不针对实现)

来源:互联网 发布:淘宝消费才送优惠券 编辑:程序博客网 时间:2024/06/05 02:29

 策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。


理解:

把代码中类似,但又有差异的算法部分,提取出来,定义一个借口,不同的算法来进行不同的实现,但调用算法的客户可以进行统一的调用,因为实现了共同的借口,客户不需要知道具体的实现,而是知道怎么用,即针对接口编程,而不针对实现编程。


  总结:

  找出代码中可能需要变换之处,把它们独立出来,不要和那些不需要变化的代码混在一起。


例子private TextClickInterface mClickInterface; // 采用策略模式,封装变化,实现点击处理
(客户)
public interface TextClickInterface{<span style="white-space:pre"></span>public void click(); // 点击事件,执行相应动作,如:预约、求片<span style="white-space:pre"></span>public void changeText(); // 修改点击后Text显示效果}(定义接口)
(实现一)public class YuyueText implements TextClickInterface{private Context context;private MarkInfo info; // 信息private TextView text; // textviewpublic YuyueText(Context context,MarkInfo info, TextView text){this.context = context;this.info = info;this.text = text;}@Overridepublic void click() {//实现预约}@Overridepublic void changeText() {//改变字体颜色及内容text.setText(R.string.mark_yuyue_success);text.setTextColor(context.getResources().getColor(R.color.mark_font_white));text.setBackgroundColor(context.getResources().getColor(R.color.mark_blue_already));Toast.makeText(context, "已预约成功", Toast.LENGTH_SHORT).show();;}}
(实现二)public class QiupianText implements TextClickInterface{private Context context;private MarkInfo info;private TextView text;public QiupianText(Context context, MarkInfo info, TextView text){this.context = context;this.info = info;this.text = text;}@Overridepublic void click() {// 求片逻辑}@Overridepublic void changeText() {// 改变text颜色、文字text.setText(R.string.mark_qiupian_success);text.setTextColor(context.getResources().getColor(R.color.mark_font_white));text.setBackgroundColor(context.getResources().getColor(R.color.mark_blue_already));Toast.makeText(context, "已发送求片请求", Toast.LENGTH_SHORT).show();}


1 0
原创粉丝点击