1 Star 4 Fork 0

foruo/foruo-learn-java

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
contribute
Sync branch
Cancel
Notice: Creating folder will generate an empty file .keep, because not support in Git
Loading...
README

设计模式 之 策略模式

定义

提供几个算法策略,选择其中一个策略去执行。

优点

  • 由于将算法封装成单独的策略,策略可以灵活切换。
  • 扩展性好,符合开闭原则。

缺点

  • 策略多,类也会变多
  • 策略类需要对外暴露

代码

场景

常见的加、减、乘、除,客户端选择其中一个算法进行计算。

代码

IOperation

/**
 * 操作接口
 * @author GaoYuan
 * @date 2018/11/11 下午2:45
 */
public interface IOperation {
    /** 执行计算 */
    int operation(int a,int b);

}

加、减、乘、除具体的算法实现类

/**
 * 加法
 */
public class AddOperation implements IOperation{

    @Override
    public int operation(int a, int b) {
        return a + b;
    }
}
/**
 * 减法
 */
public class SubOperation implements IOperation{

    @Override
    public int operation(int a, int b) {
        return a - b;
    }
}
/**
 * 乘法
 */
public class MulOperation implements IOperation{

    @Override
    public int operation(int a, int b) {
        return a * b;
    }

}
/**
 * 除法
 */
public class DivOperation implements IOperation{

    @Override
    public int operation(int a, int b){
        if(b == 0){
            return 0;
        }
        return a / b;
    }
    
}

Context

/**
 * 使用者
 * @author GaoYuan
 * @date 2018/11/11 下午2:51
 */
public class Context {

    IOperation iOperation;

    public Context(IOperation iOperation) {
        this.iOperation = iOperation;
    }

    public int execute(int a, int b){
        return iOperation.operation(a, b);
    }
}

测试

public static void main(String[] args){
    // 加
    Context context = new Context(new AddOperation());
    System.out.println(context.execute(6,2));
    // 减
    context = new Context(new SubOperation());
    System.out.println(context.execute(6,2));
    // 乘
    context = new Context(new MulOperation());
    System.out.println(context.execute(6,2));
    // 除
    context = new Context(new DivOperation());
    System.out.println(context.execute(6,2));
}

结果输出:

8
4
12
3

策略模式 与 状态模式 区别

相同点

  • 类的结构都差不多

不同点

  • 状态模式 侧重 状态之间的切换,在状态A执行完毕后自己控制状态指向状态B,根据状态改变行为。
  • 策略模式 侧重 调用者选择其中一种策略进行执行。根据不同的条件选择不同的策略。

策略模式 与 简单工厂模式 区别

相同点

  • 最终结果是一致的,都是根据某个情景,执行最终的算法

不同点

概念上,或者说最本质的区别

  • 简单工厂模式属于创建型模式,调用者,根据条件,可以获取直接创建好的目标对象,然后调用该对象对应的方法即可。
  • 策略模式属于行为型模式,调用者需要先创建Context对象,然后自行选择算法,以便具体调用。

当然,在一定程度上,两者也可以相结合。

码云

https://gitee.com/gmarshal/foruo-learn-java/tree/master/src/main/java/com/foruo/learn/designmode/strategy

博客

https://my.oschina.net/gmarshal/blog/2876104

欢迎关注我的个人微信订阅号:(据说这个头像程序猿专用)

输入图片说明

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/gmarshal/foruo-learn-java.git
git@gitee.com:gmarshal/foruo-learn-java.git
gmarshal
foruo-learn-java
foruo-learn-java
master

Search