抽象方法与接口 [英] Abstract method vs interface

查看:112
本文介绍了抽象方法与接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构我的代码,所以我需要做出关于接口或抽象类的决定。
我有基类播放器和继承基类的类,它们被称为VideoPlayer,MusicPlayer等。基类有抽象方法,没有实现(Play)。
那么,什么是更好的方式?将Play放入界面或将其保留在抽象类中。在MusicPlayer中播放与VideoPlayer中的播放器不同。我在C#中这样做。

I'm refactoring my code, so I need make decision about interface or abstract class. I have base class Player and classes that inherit base class which are called VideoPlayer, MusicPlayer and so on. Base class have abstract method with no implementation (Play). So, What is preferable way? Put Play in interface or leave it in abstract class. Play in MusicPlayer is not same like Player in VideoPlayer. I do that in C#.

class Player
{
    abstract void Play();
} 

class VideoPlayer : Player
{
    void Play()
    {
      //Some code.
    }
}

class MusicPlayer : Player
{
    void Play()
    {
      //Some code.
    }
}


推荐答案

一个常见的事情是两者兼顾

One common thing is to do both

a)提供接口。使用对象时使用界面(即调用play方法)。

a) provide the interface. And use the interface when you consume the object (ie invoke the play method).

b)提供一个基类,用于实现常见管道的情况下的接口;常用方法等。这是实施者可选择使用的辅助工具

b) provide a base class that implements the interface for the case where there is common plumbing; common methods etc. This is a helper for implementers to optionally use

这样,IAmAPlayer的实现者可以简单地实现该接口,或者如果他们的用例与您的基类匹配,可以用那个。

IN this way an implementer of IAmAPlayer can simply implement that interface or if their use case matches your base class they can use that.

这篇关于抽象方法与接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆