盒子
盒子

策略模式

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

  1. 定义算法族
1
2
3
public interface FlyBehavior {
String fly(); // 飞的行为
}
1
2
3
public interface QuackBehavior {
String quack(); // 叫的行为
}
1
2
3
4
5
6
public class FlyNoWay implements FlyBehavior {	
@Override
public String fly() {
return "I can't fly";
}
}
1
2
3
4
5
6
public class FlyRocketPowered implements FlyBehavior {  
@Override
public String fly() {
return "I'm flying with a rocket";
}
}
1
2
3
4
5
6
public class MuteQuack implements QuackBehavior {
@Override
public String quack() {
return "Silence";
}
}
1
2
3
4
5
6
public class Quack implements QuackBehavior {
@Override
public String quack() {
return "Quack";
}
}
  1. 客户使用算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ModelDuck extends Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;

public ModelDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Quack();
}

@Override
public String display() {
return "I'm a model duck";
}
}

其中Duck类为:

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
public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;

public Duck(){
}

public abstract String display();

public String performFly(){
return flyBehavior.fly();
}

public String performQuack(){
return quackBehavior.quack();
}

public String swim(){
return "All ducks float";
}

public void setFlyBehavior(FlyBehavior flyBehavior){
this.flyBehavior = flyBehavior;
}

public void setQuackBehavior(QuackBehavior quackBehavior){
this.quackBehavior = quackBehavior;
}
}

体现设计原则: 发现变化,封装变化 多用组合,少用继承 针对接口编程,而非实现编程

支持一下
扫一扫,支持沈健
  • 微信扫一扫
  • 支付宝扫一扫