您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 资本运营 > 设计模式实验1 策略模式
1实验报告课程:设计模式实验学期:2010-2011学年第一学期任课教师:专业:学号:姓名:成绩:实验1策略模式1.题目:在教材25页上,有一堆杂乱的类与接口,选取自一个动作冒险游戏。我们能看到代表游戏角色的类和角色可以使用的武器行为的类。每个角色一次只能使用一种武器,但是可以在游戏的过程中换武器,使用策略模式完成实验要求。2.模式设计的UML类图:3.程序源代码:(1)角色抽象类Character.java:publicabstractclassCharacter{WeaponBehaviorweaponBehavior;publicCharacter(){};publicabstractvoiddisplay();publicvoidfight()//委托给行为类{weaponBehavior.useWeapon();}2publicvoidsetWeaponBehavior(WeaponBehaviorwb)//设置武器类型{weaponBehavior=wb;}}(2)继承角色抽象类的各个子类:publicclassKingextendsCharacter{publicKing(){weaponBehavior=newSwordBehavior();//初始化武器类型}publicvoiddisplay(){System.out.print(King:);}}publicclassQueenextendsCharacter{publicQueen(){weaponBehavior=newKnifeBehavior();//初始化武器类型}publicvoiddisplay(){System.out.print(Queen:);}}publicclassKnightextendsCharacter{publicKnight(){weaponBehavior=newBowAndArrowBehavior();//初始化武器类型}publicvoiddisplay(){System.out.print(Knight:);}}publicclassTrollextendsCharacter{publicTroll(){weaponBehavior=newAxeBehavior();//初始化武器类型}publicvoiddisplay(){System.out.print(Troll:);}}3(3)武器行为的接口WeaponBehavior.java:publicinterfaceWeaponBehavior{publicvoiduseWeapon();}(4)实现武器行为接口的各个子类:publicclassAxeBehaviorimplementsWeaponBehavior{publicvoiduseWeapon(){System.out.println(用斧头砍劈!(AxeBehavior));}}publicclassBowAndArrowBehaviorimplementsWeaponBehavior{publicvoiduseWeapon(){System.out.println(用弓箭射击!(BowAndArrowBehavior));}}publicclassKnifeBehaviorimplementsWeaponBehavior{publicvoiduseWeapon(){System.out.println(用匕首刺杀!(KnifeBehavior));}}publicclassSwordBehaviorimplementsWeaponBehavior{publicvoiduseWeapon(){System.out.println(用宝剑刺杀!(SwordBehavior));}}(5)角色打斗的主类CharacterFight.java:publicclassCharacterFight{publicstaticvoidmain(String[]args){Characterking=newKing();Characterqueen=newQueen();Characterknight=newKnight();Charactertroll=newTroll();king.display();4System.out.print(妖怪过来了,让我);king.fight();queen.display();System.out.print(我手里有匕首,我);queen.fight();troll.display();System.out.print(哈哈,我不怕你们,我);troll.fight();knight.display();System.out.print(国王小心,让我);knight.fight();king.display();System.out.print(你的射击水平太差了,还是让我来吧,我);king.setWeaponBehavior(newBowAndArrowBehavior());//更换武器king.fight();troll.display();System.out.print(哈哈,你们完蛋了,我也有弓箭,);troll.setWeaponBehavior(newBowAndArrowBehavior());//更换武器troll.fight();king.display();System.out.println(骑士,用你的斧头啊!给我使劲劈死他。);knight.display();System.out.print(是,国王,妖怪,拿命来吧!);knight.setWeaponBehavior(newAxeBehavior());//更换武器knight.fight();troll.display();System.out.println(啊啊...,你的斧头还厉害啊,我败了。);}}
本文标题:设计模式实验1 策略模式
链接地址:https://www.777doc.com/doc-4398505 .html