Single responsibility principle in programming

        There are seven principles in the software design model, namely the single responsibility principle, the opening and closing principle, the Richter substitution principle, the dependency inversion principle, the interface isolation principle, the composite reuse principle and the Dimit's principle.
        Let's talk about the Single Responsibility Principle (Single Responsibility Principle, SRP).
        1. Definition
        of the Single Responsibility Principle The responsibility of a class is single, and only one function is provided externally, and there should be only one reason for class changes.
        2. Case
        1.1 Original design 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 Design ver1.2 with single responsibility added

#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;
}

        Version ver1.2 has better maintainability and scalability than ver1.1 code.

Guess you like

Origin blog.csdn.net/sanqima/article/details/105327932