首页 > 代码库 > 【java设计模式】【行为模式Behavioral Pattern】策略模式Strategy Pattern

【java设计模式】【行为模式Behavioral Pattern】策略模式Strategy Pattern

 1 package com.tn.策略模式;
 2 
 3 public class Client {
 4     private Strategy strategy;
 5     public void setStrategy(Strategy strategy){
 6         this.strategy=strategy;
 7     }
 8     public void exeAlgorithm() {
 9         strategy.exeAlgorithm();
10     }
11     
12     public static void main(String[]args){
13         Strategy strategy1=new ConcreteStrategy1();
14         Strategy strategy2=new ConcreteStrategy2();
15         Strategy strategy3=new ConcreteStrategy3();
16         
17         Client c=new Client();
18         
19         c.setStrategy(strategy1);
20         c.exeAlgorithm();
21         
22         c.setStrategy(strategy2);
23         c.exeAlgorithm();
24         
25         c.setStrategy(strategy3);
26         c.exeAlgorithm();
27     }
28 }
29 interface Strategy{
30     void exeAlgorithm();
31 }
32 class ConcreteStrategy1 implements Strategy{
33     @Override
34     public void exeAlgorithm() {
35         System.out.println("执行算法1……");
36     }
37 }
38 class ConcreteStrategy2 implements Strategy{
39     @Override
40     public void exeAlgorithm() {
41         System.out.println("执行算法2……");
42     }
43 }
44 class ConcreteStrategy3 implements Strategy{
45     @Override
46     public void exeAlgorithm() {
47         System.out.println("执行算法3……");
48     }
49 }

 

【java设计模式】【行为模式Behavioral Pattern】策略模式Strategy Pattern