【问题标题】:Base class implementing interface基类实现接口
【发布时间】:2016-07-22 10:40:12
【问题描述】:
  1. 基类实现接口有哪些缺点/风险?
  2. 总是在子类上实现接口会更好吗?
  3. 您什么时候会使用其中一种?

    public interface IFriendly
    {
        string GetFriendly();
    }
    
    
    public abstract class Person: IFriendly
    {
        public abstract string GetFriendly(); 
    }
    

    VS.

    public interface IFriendly
    {
        string GetFriendly();
    }
    
    public abstract class Person
    {
       // some other stuff i would like subclasses to have
    }
    
    public abstract class Employee : Person, IFriendly
    {
        public string GetFriendly()
        {
            return "friendly";
        }
    }
    

【问题讨论】:

  • ALL派生类将使用此实现时,在基类中实现;否则留下摘要。

标签: c# .net oop


【解决方案1】:

嗯,你需要这样想:

public interface IBreathing
{
    void Breathe();
}

//because every human breathe
public abstract class Human : IBreathing
{
    abstract void Breathe();
}

public interface IVillain
{
    void FightHumanity();
}

public interface IHero
{
    void SaveHumanity();
}

//not every human is a villain
public class HumanVillain : Human, IVillain
{
    void Breathe() {}
    void FightHumanity() {}
}

//but not every is a hero either
public class HumanHero : Human, IHero
{
    void Breathe() {}
    void SaveHumanity() {}
}

关键是你的基类应该实现接口(或继承但只将其定义公开为抽象)只有当从它派生的每个其他类也应该实现该接口时。 因此,根据上面提供的基本示例,只有在每个 Human 呼吸(这里是正确的)时,您才会让 Human 实现 IBreathing

但是!你不能让Human 同时实现IVillainIHero,因为这会使我们以后无法区分它是一个还是另一个。实际上,这样的实现意味着每个Human 既是反派又是英雄。

总结您的问题的答案:

  1. 基类实现接口的缺点/风险是什么?

    没有,如果从它派生的每个类也都应该实现该接口。

  2. 总是在子类上实现接口会更好吗?

    如果从基类派生的每个类也都应该实现该接口,那是必须

  3. 您什么时候会使用其中一种?

    如果从基类派生的每个类都应该实现这样的接口,则让基类继承它。如果没有,让具体类实现这样的接口。

【讨论】:

    【解决方案2】:

    从基类开始将您与基类的实现联系在一起。我们总是开始认为基类正是我们想要的。然后我们需要一个新的继承类,但它不太适合,所以我们发现自己要返回并修改基类以适应继承类的需求。它一直在发生。

    如果您从界面开始,那么您将拥有更多的灵活性。不必修改基类,您只需编写一个实现接口的新类。当它工作时你可以享受类继承的好处,但当它不工作时你不会被它束缚。

    当我第一次开始使用 OOP 时,我喜欢类继承。令人惊讶的是,它很少会变得实用。这就是 Composition Over Inheritance 的主要作用所在。最好从类的组合中构建功能,而不是将其嵌套在继承的类中。

    还有Open/Closed 原则。如果您可以继承,那就太好了,但是您不想返回并更改基类(并冒着破坏其他东西的风险),因为新继承的类需要它才能正常工作。对接口而不是基类进行编程可以使您不必修改现有的基类。

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 2020-03-13
      • 2018-02-08
      • 2010-09-30
      • 2010-09-22
      • 1970-01-01
      相关资源
      最近更新 更多