类图:
实现:
Strategy.java
package com.strategy;
public interface Strategy {
void execute();
}
StrategyA.java
package com.strategy;
public class StrategyA implements Strategy{
@Override
public void execute() {
System.out.println("StrategyA");
}
}
StrategyB.java
package com.strategy;
public class StrategyB implements Strategy {
@Override
public void execute() {
System.out.println("StrategyB");
}
}
User.java
package com.strategy;
public class User {
private Strategy strategy;
public User(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
Main.java
package com.strategy;
public class Main {
public static void main(String[] args) {
StrategyA strategyA = new StrategyA();
StrategyB strategyB = new StrategyB();
User userA = new User(strategyA);
User userB = new User(strategyB);
userA.executeStrategy(); //StrategyA
userB.executeStrategy(); //StrategyB
}
}