设计模式-策略模式

策略模式

/**
 * @USER: lynn
 * @DATE: 2020/4/26
 **/
public class 策略模式 {
    public static void main(String[] args) {
        Context context = new Context(new 微信支付());
        context.收钱();
        context.付钱();
    }

}
interface 支付{
    void 付钱();
    void 收钱();
}
class 微信支付 implements 支付{

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

    @Override
    public void 收钱() {
        System.out.println("微信收钱");
    }
}
class 支付宝支付 implements 支付{

    @Override
    public void 付钱() {
        System.out.println("支付宝付钱");
    }

    @Override
    public void 收钱() {
        System.out.println("支付宝收钱");
    }
}
class Context{
    private 支付 pay;

    public Context(支付 payWay) {
        this.pay = payWay;
    }

    public void 付钱() {
        pay.付钱();
    }

    public void 收钱() {
        pay.收钱();
    }
}
  • 优点
    • 上下文和具体策略是松耦合关系。
    • 策略模式满足"开闭原则",当新增具体策略时不需修改上下文代码。
  • 场景
    • 如果程序不希望暴露内部细节,可以使用策略模式封装
  • 应用
    • Arrays.sort(Object[],Comparator)Collections.sort(List,Comparator)
     /**
      * @USER: lynn
      * @DATE: 2020/4/26
      **/
     public class 策略模式 {
         public static void main(String[] args) {
             Integer[] integers = {
                     new Integer(1),
                     new Integer(3),
                     new Integer(5)
             } ;
             Arrays.sort(integers,new Comparator(){
                 @Override
                 public int compare(Object o1, Object o2) {
                     return ((Integer) o2).intValue()-((Integer) o1).intValue();
                 }
             });
             System.out.println(Arrays.toString(integers));
         }
     }
    

使用Lambda表达式简化策略模式

前提:函数接口(@FunctionalInterface)

/**
 * @USER: lynn
 * @DATE: 2020/4/26
 **/
public class 策略模式 {
    public static void main(String[] args) {
        Context context = new Context((int money)->{
            System.out.println("微信付钱"+money);
        });
        context.付钱(100);
    }

}
@FunctionalInterface
interface 支付{
    void 付钱(int money);

}
class Context{
    private 支付 pay;

    public Context(支付 payWay) {
        this.pay = payWay;
    }

    public void 付钱(int money) {
        pay.付钱(money);
    }
}

更多请访问Github主页 Github/Cynaith

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。