抽象类实现接口是好还是坏? [英] Is it good or bad for an abstract class to implement an interface?

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

问题描述

抽象类实现接口是好还是坏?

Is it good or bad for an abstract class to implement an interface?

以下两个例子都有效,但哪一个让对你更有意义

both examples below works, but which one makes more sense to you?

选项1,

interface A {
    function foo();
}

abstract class B implements A {
    abstract public function foo();
}

class C extends B {
    public function foo() {
        echo 'works';
    }
}

$o = new C();
$o->foo();

选项2,

interface A {
    function foo();
}

abstract class B implements A {
}

class C extends B {
    public function foo() {
        echo 'works';
    }
}

$o = new C();
$o->foo();


推荐答案

在option2中,classB不会对你的语义添加任何内容应用程序,所以完全没必要。如果您不需要在抽象类中实现某些共享(通过所有子类)功能,则应该最好直接从接口派生,以使事情不必要地复杂化。

In option2, classB adds nothing to the semantics of your application, so it is completely unnecessary. If you do not have any need to implement some shared (by all subclasses) functionality in the abstract class, you should better derive directly from the interface, to make things not unnecessarily complicated.

在这种情况下,整个事情可能有意义地简化为:

In this case, the whole thing could be sensefully simplyfied to:

interface A 
{
    function foo();
}

class C implements A 
{
    public function foo() {
        echo 'works';
    }
}

这篇关于抽象类实现接口是好还是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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