//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : DragonSlayingStrategy.java
// @ Date : 2016/8/23
// @ Author :
//
//
public interface DragonSlayingStrategy {
public void execute();
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : MeleeStrategy.java
// @ Date : 2016/8/23
// @ Author :
//
//
public class MeleeStrategy implements DragonSlayingStrategy {
public void execute()
{
System.out.println("With your Excalibur you severe the dragon's head!");
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : SpellStrategy.java
// @ Date : 2016/8/23
// @ Author :
//
//
public class SpellStrategy implements DragonSlayingStrategy {
public void execute()
{
System.out.println("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : ProjectileStrategy.java
// @ Date : 2016/8/23
// @ Author :
//
//
public class ProjectileStrategy implements DragonSlayingStrategy {
public void execute()
{
System.out.println("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
}
}
//
//
// Generated by StarUML(tm) Java Add-In
//
// @ Project : Untitled
// @ File Name : DragonSlayer.java
// @ Date : 2016/8/23
// @ Author :
//
//
/*
* DragonSlayer 使用不同的策略去杀龙.
*/
public class DragonSlayer {
private DragonSlayingStrategy strategy;
public DragonSlayer(DragonSlayingStrategy strategy)
{
this.strategy = strategy;
}
public void changeStrategy(DragonSlayingStrategy dss) {
this.strategy = dss;
}
public void gotoBattle() {
strategy.execute();
}
}
/*
* 策略(DragonSlayingStrategy) 封装一个算法.包含对象(DragonSlayer)能修改它的行为通过
* changeStrategy方法改变它的策略.
*/
public class App {
public static void main(String[] args) {
System.out.println("Green dragon spotted ahead!");
DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.gotoBattle();
System.out.println("Red dragon emerges.");
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.gotoBattle();
System.out.println("Black dragon lands before you.");
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.gotoBattle();
}
}
//Green dragon spotted ahead!
//With your Excalibur you severe the dragon's head!
//Red dragon emerges.
//You shoot the dragon with the magical crossbow and it falls dead on the ground!
//Black dragon lands before you.
//You cast the spell of disintegration and the dragon vaporizes in a pile of dust!
java设计模式进阶_strategy
最新推荐文章于 2024-08-13 22:29:45 发布