设计原则:
#找出应用中可能需要变化之处,把它们独立出来,不要和不需要变化的代码混在一起(即使是行为)
#针对接口编程,而不是针对实现编程。(实例化对象时使用多态) #多用组合,少用继承策略模式:定义了算法族,分别封装起来,让他们可以互相替换,此模式让算法的变化独立与使用算法的客户
Strategy模式的UML类别结构图如下:
环境:顾客或用户需要别的东西,或者想要新动能;公司决定采用别的数据库产品,又从另一家厂商买了数据,造成数据格式不兼容
例:一群鸭子,有些会飞,有些会叫,有些会游泳等,会添加新功能。不同种类的特性不一样
用Strategy实现,UML图如下:
代码:FlyBehavior.java (将飞行行为封装成接口)
1 public interface FlyBehavior {
2 void fly();
3 }
FlyWithWings.java (具体实现接口的类)
1 public class FlyWithWings implements FlyBehavior {
2 public void fly() {
3 System.out.println("I'm is flying");
4
5 }
6}
FlyNoWay.java
1 public class FlyNoWay implements FlyBehavior {
2 public void fly() {
3 System.out.println("I can't fly!");
4 }
5 }
6
QuackBehavior.java(将叫喊行为封装成接口)
1 public interface QuackBehavior {
2 void Qquack();
3 }
Quack.java(具体实现叫喊的类)
1 public class Quack implements QuackBehavior {
2 public void Qquack() {
3 System.out.println("quack,quack");
4 }
5 }
6
Squeak.java MuteQuack.java 类似的实现叫喊接口的类
........................
Duck.java
1 public abstract class Duck {
2 FlyBehavior flyBehavior;
3 QuackBehavior quackBehavior;
4
5 public void Swin() {
6 System.out.println("I'm swining!");
7 }
8
9 public abstract void display();
10
11 public void performFly() {
12 flyBehavior.fly();
13 }
14
15 public void performQuack() {
16 quackBehavior.Qquack();
17 }
18
19 public void setFlyBehavior(FlyBehavior flyBehavior) {
20 this.flyBehavior = flyBehavior;
21 }
22
23 public void setQuackBehavior(QuackBehavior quackBehavior) {
24 this.quackBehavior = quackBehavior;
25 }
26
27
28 }
MallardDuck.java
1 public class MallardDuck extends Duck {
2 public MallardDuck() {
3 flyBehavior = new FlyNoWay();
4 quackBehavior = new Quack();
5 }
6
7 @Override
8 public void display() {
9 System.out.println("I'm a MallarDuck!");
10
11 }
12
13 }
14
RedheadDuck RubberDuck 类似继承Duck实现以上方法....
最后Main.java....
1 public class Main {
2 public static void main(String[] args) {
3 Duck mallardDuck = new MallardDuck();
4 mallardDuck.display();
5 mallardDuck.performQuack();
6 mallardDuck.performFly();
7 System.out.println();
8
9 Duck redheadDuck = new RedheadDuck();
10 redheadDuck.display();
11 redheadDuck.performQuack();
12 redheadDuck.performFly();
13 System.out.println();
14 }
若想增加一个模型鸭,原本不会FLY,后面加了火箭会飞了,
首先,添加个继承Duck的ModelDuck类.方法与上面相似,然后添加个实现飞行接口的类.
FlyRocketPower.java
1 public class FlyRocketPower implements FlyBehavior {
2 public void fly() {
3 System.out.println("I'm flying with a rocket!");
4
5 }
6 }
7
在Main类中加一下:
1 Duck modelDuck = new ModelDuck();
2 modelDuck.performQuack();
3 modelDuck.performFly();
4 modelDuck.setFlyBehavior(new FlyRocketPower());
5 modelDuck.performFly();
运行下,一切皆有可能~~~