可以做免费推广的网站,数码产品商城网站建设,企业官网制作费用,centos yum wordpress概念#xff1a; 策略模式定义了一系列的算法#xff0c;并将每一个算法封装起来#xff0c;而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。 #xff08;原文#xff1a;The Strategy Pattern defines a family of algorithms,encapsula…概念 策略模式定义了一系列的算法并将每一个算法封装起来而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。 原文The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. 抽象策略角色 策略类通常由一个接口或者抽象类实现。 步骤 ①②步比较菜忽略。有异议者联系 ①首先定义一个策略接口 ②然后再写出你需要的实现类这里称为“计谋”去继承①策略接口。 ③计谋有了那还要有锦囊装 /** * author wonter * b描述:/b计谋有了那还要有锦囊装 br * b邮件/b yiyu1163.com br */ public class Box { //①策略接口 private IStrategy straegy; //向锦囊中传入计谋 //这里类型是策略IStrategy接口但传入的则是“实现”接口的计谋。 public Box(IStrategy jimou){ //改写策略 this.straegy jimou; } //使用计谋 public void operate(){ this.straegy.operate(); } } ④使用计谋 /** * author wonter * b描述:/b计谋有了那还要有锦囊装 br * b邮件/b yiyu1163.com br */ public class YunZhao { public static void main(String[] args) { //将锦囊声明出来 Context context; System.out.println(—— 锦囊妙计一 ——); //向锦囊拿出**计谋 context new Context(new first()); //执行计谋 context.operate(); System.out.println(—— 锦囊妙计二 ——); //向锦囊拿出**计谋 context new Context(new second()); //执行计谋 context.operate(); System.out.println(—— 以下待为扩展 ——); System.out.println(—— ... .... ——); 好处 这就是策略模式高内聚低耦合的特点也表现出来了。 还有一个就是扩展性也就是 OCP原则只要修改 Context.java 就可以了。 提供了一种替代继承的方法而且既保持了继承的优点(代码重用)还比继承更灵活(算法独立可以任意扩展)。 避免程序中使用多重条件转移语句使系统更灵活并易于扩展。 /** * author wonter * b描述:/b 一天学一个模式 更新中请关注我的博客 br * b博客:/b http://www.cnblogs.com/Javame br * b邮件/b yiyu1163.com br */