软件的设计模式中有七大原则,分别为单一职责原则、开闭原则、里氏代换原则、依赖倒转原则、接口隔离原则、合成复用原则和迪米特法则。
下面说说,单一职责原则(Single Responsibility Principle,SRP)。
一、单一职责原则的定义
类的职责单一,对外只提供一种功能,而引起类变化的原因都应该只有一个。
二、案例
1.1 原设计 ver1.1
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Clothes
{
public:
void working(){
cout << "工作方式" << endl;
}
void shopping() {
cout << "逛街方式" << endl;
}
};
int main(void)
{
//工作
Clothes cs;
cs.working();
//逛街
cs.shopping();
return 0;
}
1.2 加入了单一职责的设计 ver1.2
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class WorkingClothes
{
public:
void style(){
cout << "逛街方式" << endl;
}
};
class ShoppingClothes
{
public:
void style(){
cout << "工作方式" << endl;
}
};
int main(void)
{
WorkingClothes workCS;
workCS.style();
ShoppingClothes shopCS;
shopCS.style();
return 0;
}
版本ver1.2 比ver1.1代码的可维护性、可扩展性要好。