美文网首页
策略模式

策略模式

作者: Neo_xu | 来源:发表于2018-09-19 22:55 被阅读0次

概念

一个类的行为或其算法可以在运行时更改

角色

  • 共同特性的抽象方法
  • 各个不同的算法对象
  • 选择算法的 context对象

利弊

  • 扩展方便
  • 耦合低

demo

支付的场景

// 算法的抽象接口
public interface Pay {
   public void pay();
}
public class AliPay implements Pay {
    @Override
    public void pay() {
        System.out.println("阿里支付");
    }

}
public class WeChatPay implements Pay {

    @Override
    public void pay() {
        System.out.println("微信支付");
    }

}

public class PayStrategy {
    private Pay pay;
    PayStrategy(Pay pay){
        this.pay = pay;
    }
    public void exePay(){
        pay.pay();
    }
}
public class PayStrategyTest {
    public static void main(String[] args) {
        PayStrategy  strategy  = new PayStrategy(new AliPay());
        strategy.exePay();
        strategy = new PayStrategy(new WeChatPay());
        strategy.exePay();
    }

}

拓展

对于策略太多,可以使用策略列表进行策略匹配

相关文章

网友评论

      本文标题:策略模式

      本文链接:https://www.haomeiwen.com/subject/ebfmnftx.html