参考鸿洋大神的博客学习一下设计模式
设计模式是设计一种容易了解、容易维护、具有弹性的架构的理论基础。
总结一下OO的原则:
1、封装变化(把可能变化的代码封装起来)
2、多用组合,少用继承(我们使用组合的方式,为客户设置了算法)
3、针对接口编程,不针对实现(对于Role类的设计完全的针对角色,和技能的实现没有关系)
策略模式
定义了算法族,分别封装起来,让它们之间可相互替换,此模式让算法的变化独立于使用算法的客户。
public interface IAttackBehavior
{
void attack();
}
public interface IDefendBehavior
{
void defend();
}
public interface IDisplayBehavior
{
void display();
}
public class AttackJY implements IAttackBehavior
{
@Override
public void attack()
{
System.out.println("九阳神功!");
}
}
public class DefendTBS implements IDefendBehavior
{
@Override
public void defend()
{
System.out.println("铁布衫");
}
}
public class RunJCTQ implements IRunBehavior
{
@Override
public void run()
{
System.out.println("金蝉脱壳");
}
}
/**
* 游戏的角色超类
*
* @author zhy
*
*/
public abstract class Role
{
protected String name;
protected IDefendBehavior defendBehavior;
protected IDisplayBehavior displayBehavior;
protected IRunBehavior runBehavior;
protected IAttackBehavior attackBehavior;
public Role setDefendBehavior(IDefendBehavior defendBehavior)
{
this.defendBehavior = defendBehavior;
return this;
}
public Role setDisplayBehavior(IDisplayBehavior displayBehavior)
{
this.displayBehavior = displayBehavior;
return this;
}
public Role setRunBehavior(IRunBehavior runBehavior)
{
this.runBehavior = runBehavior;
return this;
}
public Role setAttackBehavior(IAttackBehavior attackBehavior)
{
this.attackBehavior = attackBehavior;
return this;
}
protected void display()
{
displayBehavior.display();
}
protected void run()
{
runBehavior.run();
}
protected void attack()
{
attackBehavior.attack();
}
protected void defend()
{
defendBehavior.defend();
}
}
public class RoleA extends Role
{
public RoleA(String name)
{
this.name = name;
}
}
public class Test
{
public static void main(String[] args)
{
Role roleA = new RoleA("A");
roleA.setAttackBehavior(new AttackXL())//
.setDefendBehavior(new DefendTBS())//
.setDisplayBehavior(new DisplayA())//
.setRunBehavior(new RunJCTQ());
System.out.println(roleA.name + ":");
roleA.run();
roleA.attack();
roleA.defend();
roleA.display();
}
}