接口隔离原则(Interface segregation principle)

接口隔离原则(Interface segregation principle)

flyfish

一些对接口隔离原则的描述

Clients should not be forced to depend upon interfaces that they don’t use.

Client不应该被迫依赖他们不使用的接口

Many client specific interfaces are better than one general purpose
interface

多个Client特定的接口好于一个通用接口

The dependency of one class to another one should depend on the
smallest possible interface

类之间的依赖关系应该依赖最小接口

Make fine grained interfaces that are client specific.

制定好的粒度的接口就是针对不同的Client制定特定的接口

This principle deals with the disadvantages of fat interfaces. Fat
interfaces are not cohesive. In other words the interfaces of classes
should be broken into groups of member functions

这个原则处理胖接口(fat interface)的问题,胖接口内聚性不够好。换句话说,这种类应该分解成多组成员函数。一个类依赖于一组成员函数

The interface-segregation principle (ISP) states that no client should
be forced to depend on methods it does not use. ISP splits interfaces
that are very large into smaller and more specific ones so that
clients will only have to know about the methods that are of interest
to them.

Client不应该被迫依赖他们不使用的接口。ISP将大的接口分割成小的,更有针对性的接口,Client只关心与它们相关的接口。

代码示例

//不好的例子,机器人不吃饭的

// interface segregation principle - bad example

#include "stdafx.h"
class IWorker 
{
public:
    virtual void work(){}
    virtual void eat() {}
};

class Worker :public IWorker {
public:
    void work() 
    {
        // ....working
    }
     void eat()
     {
        // ...... eating in launch break
     }
};

class Robot :public IWorker
{
public:
    void work() 
    {
        //.... working much more
    }

     void eat() 
     {
        //.... eating in launch break
    }
};

class Manager 
{
private:
    IWorker worker;
public:
     void setWorker(IWorker w) 
     {
        worker = w;
     }

    void manage() 
    {
        worker.work();
    }
};
int main()
{
    return 0;
}

//好的例子

//// interface segregation principle - good example


class IWorkable
{
public:
    void work() {}
};

class IFeedable
{
public:
    void eat() {};
};

class Worker :public IWorkable, public IFeedable
{
public:
    void work()
    {
        // ....working
    }

    void eat()
    {
        //.... eating in launch break
    }
};

class Robot :public IWorkable
{
public: void work()
{
    // ....working
}
};


class Manager
{
public:
    IWorkable worker;

    void setWorker(IWorkable w)
    {
        worker = w;
    }

    void manage()
    {
        worker.work();
    }
};

你可能感兴趣的:(设计模式,设计模式)