策略模式

模式定义

定义了算法族,分别封装起来,让它们之间可以互相替换,此模式的变化独立于算法的使用者。

image-20230423142656652

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
public class StrategyTest {
public static void main(String[] args) {
Context context = new Context(new GreenPen());
context.executeDraw(10,0,0);
}
}

interface Strategy{
public int draw(int radius, int x, int y );
}

class RedPen implements Strategy{

@Override
public int draw(int radius, int x, int y) {
System.out.println("使用红笔画画.");
return radius;
}
}

class GreenPen implements Strategy{

@Override
public int draw(int radius, int x, int y) {
System.out.println("使用绿笔画画.");
return radius;
}
}

class Context{
private Strategy strategy;

public Context(Strategy strategy) {
this.strategy = strategy;
}

public int executeDraw(int radius, int x, int y) {
return strategy.draw(radius,x,y);
}
}

image-20230423143811170