【发布时间】:2019-06-21 16:51:05
【问题描述】:
假设,在代码中,我们有一个 IEnemy 接口,它上面有一个名为 Attack() 的方法。假设我们有五个来自 IEnemy 接口的敌人。在其中三个类中,我们使用完全相同的 Attack 方法实现。在其中之一中,我们也使用相同的代码,但在方法的某处更改了一两行代码。而且,在最后一个类中,我们仍然有相同的实现,但是在方法的某处添加/删除了一两行代码。您对解耦这段代码有什么建议吗?
我尝试过重写方法,如果我们在方法中间更改某些内容,则该方法不起作用。 我尝试使用委托作为参数,当我们想在方法中的其他地方更改某些内容时,它不起作用。 我尝试使用接口的扩展方法来制作默认实现,但其中两个类仍然具有解耦代码。
interface IEnemy
{
void Attack();
}
class Enemy1 : IEnemy
{
public void Attack()
{
Console.WriteLine("This is an enemy");
Console.WriteLine("Enemy is jumping");
Console.WriteLine("Enemy is attacking");
}
}
class Enemy2 : IEnemy
{
public void Attack()
{
Console.WriteLine("This is an enemy");
Console.WriteLine("Enemy is jumping");
Console.WriteLine("Enemy is attacking");
}
}
class Enemy3 : IEnemy
{
public void Attack()
{
Console.WriteLine("This is an enemy");
Console.WriteLine("Enemy is jumping");
Console.WriteLine("Enemy is attacking");
}
}
//Let's say this enemy is not capable of jumping, so we want to remove the code that says enemy is jumping.
class Enemy4 : IEnemy
{
public void Attack()
{
Console.WriteLine("This is an enemy");
Console.WriteLine("Enemy is attacking");
}
}
//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 : IEnemy
{
public void Attack()
{
Console.WriteLine("This is an enemy");
Console.WriteLine("Enemy is roaring");
Console.WriteLine("Enemy is attacking");
}
}
【问题讨论】:
-
您应该使用基类来代替
virtual实现,如果需要,可以覆盖该实现,或者使用默认的基类实现。 -
但是当我想在方法的中间改变一些东西时,我不能在不解耦的情况下改变它,所以我仍然需要重新编写实现,不是吗?
-
@HeroOfSkies 在你的情况下不是直接的,即使是抽象的,但是如果敌人可以跳跃或咆哮或其他什么,它必须是父类可用的通用布尔属性。然后父类可以使用 if / else 语句显示正确的消息。
-
@Franck 谢谢你的回答,也谢谢你的建议:)
-
您可以将跳跃、攻击和咆哮隔离到它们自己的类中,
IEnemy可以通过一些抽象来依赖它们。这样,每个敌人都只是各种行为的组合,而不是使用继承。
标签: c# oop interface polymorphism decoupling