您的位置:首页 > 移动开发 > Android开发

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

2015-05-08 15:29 204 查看
策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。理解:把代码中类似,但又有差异的算法部分,提取出来,定义一个借口,不同的算法来进行不同的实现,但调用算法的客户可以进行统一的调用,因为实现了共同的借口,客户不需要知道具体的实现,而是知道怎么用,即针对接口编程,而不针对实现编程。 总结: 找出代码中可能需要变换之处,把它们独立出来,不要和那些不需要变化的代码混在一起。
例子
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; // textview		public YuyueText(Context context,MarkInfo info, TextView text){		this.context = context;		this.info = info;		this.text = text;	}	@Override	public void click() {		//实现预约	}	@Override	public 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;	}	@Override	public void click() {		// 求片逻辑	}	@Override	public 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();	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐