您的位置:首页 > 编程语言 > Java开发

java设计模式进阶_strategy

2016-08-23 10:31 387 查看


//
//
//  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设计模式