- 属于创建型设计模式
- 将一组算法封装起来,可以相互交换
今天通过策略模式来实现各个动物之间的交换
public class StrategyManager {
private ZooStrategy strategy;
public StrategyManager(ZooStrategy strategy) {
this.strategy = strategy;
}
public void changeStrategy(ZooStrategy strategy) {
this.strategy = strategy;
}
public void execute() {
strategy.execute();
}
}
public interface ZooStrategy {
void execute();
}
public class ElephantStrategy implements ZooStrategy {
@Override
public void execute() {
System.out.println("I am elephant");
}
}
public class BirdStrategy implements ZooStrategy {
@Override
public void execute() {
System.out.println("I am bird");
}
}
public class MonkeyStrategy implements ZooStrategy {
@Override
public void execute() {
System.out.println("I am monkey");
}
}
// 测试类
public class Main {
public static void main(String[] args) {
System.out.println("go to zoo to see animal");
System.out.println("to see elephant");
StrategyManager manager = new StrategyManager(new ElephantStrategy());
manager.execute();
System.out.println("to see bird");
manager.changeStrategy(new BirdStrategy());
manager.execute();
System.out.println("to see monkey");
manager.changeStrategy(new MonkeyStrategy());
manager.execute();
}
}
// 测试结果
go to zoo to see animal
to see elephant
I am elephant
to see bird
I am bird
to see monkey
I am monkey