【设计模式】策略模式

来源:互联网 发布:贵州广电网络公司地址 编辑:程序博客网 时间:2024/06/06 02:07

使用频率:★★★★☆

什么是策略模式

对象的行为,在不同的环境下,有不同的实现;

比如人的上班行为,在不同的环境下,可以选择走路上班或者开车上班,由客户端根据情况决定采用何种策略;

补充说明

符合“开闭原则”,可以在不修改原有代码的基础上替换、添加新的策略;

不同的策略可以相互替换;

客户端自己决定在什么情况下使用什么具体策略角色;

与状态模式区别:使用策略模式时,客户端手动选择策略,使用状态模式时,其行为是根据状态是自动切换的。

角色

抽象策略

具体策略

环境

例子,JAVA实现

例子描述:人上班,使用步行或者开车上班;

策略:步行上班、开车上班...

关系图

抽象策略接口

package com.pichen.dp.behavioralpattern.strategy;public interface IStrategy {    public void execute();}

具体策略

复制代码
package com.pichen.dp.behavioralpattern.strategy;public class DriveStrategy implements IStrategy{    /**     * @see com.pichen.dp.behavioralpattern.strategy.IStrategy#execute()     */    @Override    public void execute() {        System.out.println("driving。。。");    }}
复制代码
复制代码
package com.pichen.dp.behavioralpattern.strategy;public class WalkStrategy implements IStrategy{    /**     * @see com.pichen.dp.behavioralpattern.strategy.IStrategy#execute()     */    @Override    public void execute() {        System.out.println("walking。。。");    }}
复制代码

环境

复制代码
package com.pichen.dp.behavioralpattern.strategy;public class Context {    IStrategy strategy;        public Context(IStrategy strategy) {        this.strategy = strategy;    }        public void execute() {        this.strategy.execute();    }}
复制代码

客户端

复制代码
package com.pichen.dp.behavioralpattern.strategy;public class Main {    public static void main(String[] args) {        Context context = null;        context = new Context(new WalkStrategy());        context.execute();        context = new Context(new DriveStrategy());        context.execute();    }}
复制代码

结果打印

walking。。。driving。。。

 JDK中的示例,Collections.sort方法

不需为新的对象修改sort()方法,你需要做的仅仅是实现你自己的Comparator接口:

复制代码
        Collections.sort(            list,   //待排序的集合            new Comparator<>(){  //具体排序策略            @Override              public int compare(A a1, A a2) {                  return ; //具体大小判断规则             }          });  
复制代码

 


@author   风一样的码农
@blog_url http://www.cnblogs.com/chenpi/
分类: 设计模式
标签: DesignPattern, JAVA
好文要顶关注我 收藏该文
风一样的码农
关注 - 4
粉丝 - 224
+加关注
0
0
«上一篇:【设计模式】迭代器模式
»下一篇:【设计模式】状态模式
0 0
原创粉丝点击