Java设计模式(行为型)之-策略模式

Java设计模式(行为型)之-策略模式

行为型模式,共11种:策略模式模板方法模式观察者模式迭代子模式责任链模式命令模式备忘录模式状态模式访问者模式中介者模式解释器模式

先看看11行为型模式的关系:

这里写图片描述

策略模式(strategy)

策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数,关系图如下:

这里写图片描述

图中接口 ICalculator 提供统一的方法,
AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每个类:

public class StrategyTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String exp="2+8";
        Plus plus=new Plus();
        int result=plus.caculate(exp);
        System.out.println(result);
    }
}

// 接口,提供统一方法
interface ICaculator
{
    public int caculate(String exp);
}

// 辅助类,提供辅助方法
abstract class AbstractCaculator 
{
    public int[] split(String exp,String opt){
        String[] array=exp.split(opt);
        int[] Intarray=new int[2];
        Intarray[0]=Integer.parseInt(array[0]);
        Intarray[1]=Integer.parseInt(array[1]);
        return Intarray;
    }
}

// 三个实现类
class Plus extends AbstractCaculator implements ICaculator
{
    @Override
    public int caculate(String exp) {
        int[] IntArray=split(exp, "\\+");   
        return IntArray[0]+IntArray[1];
    }   
}

class Minus  extends AbstractCaculator implements ICaculator
{
    @Override
    public int caculate(String exp) {
        int[] IntArray=split(exp, "-"); 
        return IntArray[0]-IntArray[1];
    }   
}

class Multiply extends AbstractCaculator implements ICaculator
{
    @Override
    public int caculate(String exp) {
        int[] IntArray=split(exp, "\\*");   
        return IntArray[0]*IntArray[1];
    }   
}

输出:10
策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值