2 回答
TA贡献1963条经验 获得超6个赞
我会将接口替换为具有默认实现的抽象基类,然后将Attack方法分解为单独的可重写步骤。我Attack为完全拥有自己的攻击模式的敌人制作了虚拟。
abstract class BaseEnemy {
public virtual void Attack() {
AttackIdentify();
AttackSignal();
AttackAttack();
}
protected virtual void AttackIdentify() {
Console.WriteLine("This is an enemy");
}
protected virtual void AttackSignal() {
Console.WriteLine("Enemy is jumping");
}
protected virtual void AttackAttack() {
Console.WriteLine("Enemy is attacking");
}
}
class Enemy1 : BaseEnemy {
protected override void AttackIdentify() {
Console.WriteLine("This is an enemy 1");
}
}
class Enemy2 : BaseEnemy {
}
class Enemy3 : BaseEnemy {
protected override void AttackIdentify() {
Console.WriteLine("This is an enemy 3");
}
}
//Let's say this enemy is not capable of jumping, so we want to remove the code that says enemy is jumping.
class Enemy4 : BaseEnemy {
protected override void AttackSignal() { }
}
//Let's say this is the boss and instead of jumping, it will roar.
//So we want to change the code that says enemy is jumping to enemy is roaring.
class Enemy5 : BaseEnemy {
protected override void AttackSignal() {
Console.WriteLine("Enemy is roaring");
}
}
如果您仍然需要该接口IEnemy,则可以BaseEnemy实现它。
TA贡献1874条经验 获得超12个赞
这是它的抽象类版本的基本示例。
public abstract class Enemy
{
public bool CanJump { get; set; } = false;
public bool CanRoar { get; set; } = false;
public bool CanAttack { get; set; } = false;
public virtual void Attack()
{
Console.WriteLine("This is an enemy");
if (CanJump)
{
Console.WriteLine("Enemy is jumping");
}
if (CanRoar)
{
Console.WriteLine("Enemy is roaring");
}
if (CanAttack)
{
Console.WriteLine("Enemy is attacking");
}
}
}
public class Enemy1 : Enemy
{
public Enemy1()
{
CanJump = true;
CanRoar = true;
}
}
public class Enemy2 : Enemy
{
public Enemy2()
{
CanRoar = true;
CanAttack = true;
}
}
public class Enemy3 : Enemy
{
public Enemy3()
{
CanRoar = true;
CanAttack = true;
}
public override void Attack()
{
base.Attack();
Console.WriteLine("Custom thing");
}
}
您会注意到并Enemy1以Enemy2相同的方式工作,但设置不同的属性,当您调用该Attack方法时,这些属性将相应显示。我希望您注意的有趣部分是Enemy3覆盖该方法的类。Virtual这可以通过在抽象类中创建方法来实现Enemy。
此覆盖允许仍然调用Attack类中的基类方法Enemy,而且它还显示自定义值。所以它非常灵活。
请注意,这对于提供的示例非常有效,但是通过使用您的类名,我可以轻松地假设真正的项目是什么,这不是正确的方法。您不应该为每个敌人创建一个不同的类,但这超出了问题的范围。
- 2 回答
- 0 关注
- 120 浏览
添加回答
举报