设计模式——策略模式

策略模式:定义了不同的算法,分别封装起来,让他们可以互相替换,即使算法变化了,也不会影响到使用算法的用户;

简单解释:很像一个计算器,我输入两个数字,然后按加号你就给我计算和,我按乘法你就给我计算乘积,内部算法客户端不关注,我就告诉你我想做怎样的计算,你去给我计算吧!和工厂方法有一点像,

应用场景:立马就想到解除多个if else if 的场景了

//定义策略,提供一个方法供具体策略俩实现
public abstract class Strategy {
    public abstract void  calculate();
}

// 具体算法开始实现
public class StrategyAA extends Strategy {
    @Override
    public void calculate() {
        System.out.println("实现算法A");
    }
}
public class StrategyBB extends Strategy {
    @Override
    public void calculate() {
        System.out.println("实现算法B");
    }
}

//用一个context类来维护对抽象算法类Strategy对象的引用
public class Context {
    Strategy strategy;
    public Context(Strategy strategy){
        this.strategy = strategy;
    }

    public void doWork(){
        strategy.calculate();
    }
}

开始测试:

public class Test1 {
    public static void main(String[] args) {
        Context context = null;
        context = new Context(new StrategyAA());
        context.doWork();

        context = new Context(new StrategyBB());
        context.doWork();
    }
}

但是从上面测试类1的代码我们发现是在客户端判断是用什么算法,现在我们想把这个判断交由其他类处理,于是就有了下面的策略模式与简单工厂结合的方法。

public class Context2 {
    Strategy strategy = null;

    public  Context2(String type){
        switch (type){
            case "A": strategy = new StrategyAA();
            break;
            case "B": strategy = new StrategyBB();
            break;

        }
    }
    public void ContrxtInterface(){
        strategy.AlgorithmInterface();
    }
}
//或者
public class Context2 {
    static Map<String, Strategy> operationMap = new HashMap<>();
    static {
        operationMap.put("A", new StrategyAA());
        operationMap.put("B",  new StrategyBB());
    }
    public Context2(String type){
         strategy = operationMap.get(type);
    }
    public void doWork(){
        strategy.calculate();
    }
}


public class Text2 {
    public static void main(String[] args) {
        Context2 context2A = new Context2("A");
        context2A.doWork();
        Context2 context2B = new Context2("B");
        context2B.doWork();
    }
}

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值