官术网_书友最值得收藏!

Interface Segregation Principle

The Interface Segregation Principle states that clients should only implement interfaces they actually use. They should not be forced to implement interfaces they do not use. As per the definition found on Wikipedia:

"many client-specific interfaces are better than one general-purpose interface"

What this means is that we should split large and fat interfaces into several small and lighter ones, segregating it so that smaller interfaces are based on groups of methods, each serving one specific functionality.

Let's take a look at the following leaky abstraction that violates the ISP:

interface Appliance {
    public function powerOn();
    public function powerOff();
    public function bake();
    public function mix();
    public function wash();

}

class Oven implements Appliance {
    public function powerOn() { /* Implement ... */ }
    public function powerOff() { /* Implement ... */ }
    public function bake() { /* Implement... */ }
    public function mix() { /* Nothing to implement ... */ }
    public function wash() { /* Cannot implement... */ }
}

class Mixer implements Appliance {
    public function powerOn() { /* Implement... */ }
    public function powerOff() { /* Implement... */ }
    public function bake() { /* Cannot implement... */ }
    public function mix() { /* Implement... */ }
    public function wash() { /* Cannot implement... */ }
}

class WashingMachine implements Appliance {
    public function powerOn() { /* Implement... */ }
    public function powerOff() { /* Implement... */ }
    public function bake() { /* Cannot implement... */ }
    public function mix() { /* Cannot implement... */ }
    public function wash() { /* Implement... */ }
}

Here we have an interface setting requirements for several appliance related methods. Then we have several classes implementing that interface. The problem is quite obvious; not all appliances can be squeezed into the same interface. It makes no sense for a washing machine to be forced to implement bake and mix methods. These methods need to be split each into its own interface. That way concrete appliance classes get to implement only the methods that actually make sense.

主站蜘蛛池模板: 庐江县| 十堰市| 剑川县| 阿勒泰市| 县级市| 崇仁县| 微博| 工布江达县| 翁牛特旗| 溆浦县| 柏乡县| 旌德县| 武隆县| 景泰县| 余江县| 澄迈县| 南阳市| 天门市| 南岸区| 柘城县| 当阳市| 龙川县| 台前县| 平湖市| 松溪县| 成武县| 东平县| 凤城市| 淮滨县| 东平县| 大荔县| 厦门市| 鄂伦春自治旗| 新龙县| 蓬溪县| 襄垣县| 长子县| 鲁山县| 稷山县| 永年县| 错那县|