軟件的設計模式中有七大原則,分別爲單一職責原則、開閉原則、里氏代換原則、依賴倒轉原則、接口隔離原則、合成複用原則和迪米特法則。
下面說說,單一職責原則(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代碼的可維護性、可擴展性要好。