什么是策略模式:策略模式定义算法簇分别封装起来,并使它们之间可以相互替换,该模式让算法的变化独立于调用者之外。
定义比较抽象,还是用代码来说明,我们可以定义一组行为接口,然后针对接口做不同的实现,最后通过调用不同的行为实现达到不同的效果,比方说狗吃骨头,但是玩具狗什么都不吃。
public abstract class Animal {
private EatAction eatAction;
private RunAction runAction;
public abstract void performRun();
public abstract void performEat();
public EatAction getEatAction() {
return eatAction;
}
public void setEatAction(EatAction eatAction) {
this.eatAction = eatAction;
}
public RunAction getRunAction() {
return runAction;
}
public void setRunAction(RunAction runAction) {
this.runAction = runAction;
}
}
public interface EatAction {
public void eat();
}
public interface RunAction {
public void run();
}
public class DogEat implements EatAction {
@Override
public void eat() {
System.out.println("Eat Bone");
}
}
public class DogRun implements RunAction {
@Override
public void run() {
System.out.println("run with Four legs");
}
}
public class ToyDogEat implements EatAction {
@Override
public void eat() {
System.out.println("eat nothing");
}
}
public class Main {
public static void main(String[] args){
Animal dog = new Dog();
dog.setEatAction(new DogEat());
dog.setRunAction(new DogRun());
dog.performEat();
dog.performRun();
dog.setEatAction(new ToyDogEat());
dog.performEat();
}
}