比方说,在代码中,我们有一个 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");
}
}
神不在的星期二
HUWWW
相关分类