策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
1,定义算法接口
package com.pattern.strategy.test; public interface MoveBehavior { public void move();
}
2,定义算法的实现类
下面是三个算法的实现类
a, MoveFastBehavior
package com.pattern.strategy.test; public class MoveFastBehavior implements MoveBehavior{ /**
* @see com.pattern.strategy.test.MoveBehavior#move()
*/
@Override
public void move() {
System.out.println("move fast!");
} }
b,MoveNormalBehavior
package com.pattern.strategy.test; public class MoveNormalBehavior implements MoveBehavior{ /**
* @see com.pattern.strategy.test.MoveBehavior#move()
*/
@Override
public void move() {
System.out.println("move normal!");
} }
c,MoveSlowBehavior
package com.pattern.strategy.test; public class MoveSlowBehavior implements MoveBehavior{ /**
* @see com.pattern.strategy.test.MoveBehavior#move()
*/
@Override
public void move() {
System.out.println("move slow!");
} }
3,定义客户端抽象类
package com.pattern.strategy.test; public abstract class Car { public MoveBehavior moveBehavior; public void performMove(){
moveBehavior.move();
} public void setMoveBehavior(MoveBehavior moveBehavior){
this.moveBehavior = moveBehavior;
}
}
4,定义具体客户端类
package com.pattern.strategy.test; public class BNZCar extends Car{ public BNZCar(){
moveBehavior = new MoveFastBehavior();
}
}
在构造具体的客户端类时设置使用的算法类 !!!
5,测试
package com.pattern.strategy.test; public class CarTest { public static void main(String[] args) { Car bnz = new BNZCar();
bnz.performMove();
bnz.setMoveBehavior(new MoveSlowBehavior());
bnz.performMove();
}
}
可以在执行时动态修改 算法。
执行结果:
move fast!
move slow!
类图如下所示: