S.O.L.I.D. 接口隔离原理示例

148 阅读1分钟

一个接口不应该成为一个通用的接口,一个特定类的接口总是比一个通用的接口好。

# VIOLATION
interface PlayerInterface
{
    public function run();
    public function jump();
    public function rebound();
}

class Basketball implements PlayerInterface
{
    public function run() {}
    public function jump() {}
    public function rebound() {}
}

class Football implements PlayerInterface
{
    public function run() {}
    public function jump() {}
    public function rebound() {}
}

正如你在上面看到的,Football 类被迫实现了与它无关的rebound 方法。这是一种违规行为。

# REFACTORED
interface PlayerInterface
{
    public function run();
    public function jump();
}

interface BasketballPlayerInterface
{
    public function rebound();
}

class Basketball implements PlayerInterface, BasketballPlayerInterface
{
    public function run() {}
    public function jump() {}
    public function rebound() {}
}

class Football implements PlayerInterface
{
    public function run() {}
    public function jump() {}
}

正如你所看到的,我们已经把rebound 方法移到了BasketballPlayerInterface 接口中,并且只让Basketball 类实现它。我们的Football 类不再被迫实现不相关的方法了。