1. 含义
客户不应该被强迫使用他们不需要的接口。
2. 解释
该原则用于不满足单一职责原则的情况,客户只需要知道具有内聚接口的抽象父类即可。
3. 举例说明
如果有个办公一体机,具有打印机,复印机,扫描机的功能。对于客户来说,不需要接触每个机器,只要接触办公一体机。
InterfaceSegregationPrinciple.h
#ifndef INTERFACESEGREGATIONPRINCIPLE_H
#define INTERFACESEGREGATIONPRINCIPLE_H
#include <iostream>
using namespace std;
class Integrator
{
public:
void Print();
void Copy();
void Scanner();
};
class Operator
{
public:
void Print(Integrator *integrator);
void Copy(Integrator *integrator);
void Scanner(Integrator *integrator);
};
#endif // INTERFACESEGREGATIONPRINCIPLE_H
InterfaceSegregationPrinciple.cpp
#include "InterfaceSegregationPrinciple.h"
void Integrator::Print()
{
cout << "Print" <<endl;
}
void Integrator::Copy()
{
cout << "Copy" <<endl;
}
void Integrator::Scanner()
{
cout << "Scanner" <<endl;
}
void Operator::Print(Integrator *integrator)
{
integrator->Print();
}
void Operator::Copy(Integrator *integrator)
{
integrator->Copy();
}
void Operator::Scanner(Integrator *integrator)
{
integrator->Scanner();
}
main.cpp
#include "InterfaceSegregationPrinciple.h"
Integrator *integrator = new Integrator();
Operator oper;
oper.Copy(integrator);
oper.Print(integrator);
oper.Scanner(integrator);