设计模式-策略模式

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

策略模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @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)
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      /**
      * @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)

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      /**
      * @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);
      }
      }

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 yanglau0527@gmail.com

文章标题:设计模式-策略模式

文章字数:416

本文作者:Cynaith

发布时间:2020-05-02, 01:22:59

最后更新:2020-05-02, 01:23:57

原始链接:https://cynaith.github.io/2020/05/02/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏