Solid 원칙
C++
Solid 원칙
Solid 원칙
객체 지향 프로그래밍의 5가지 설계 원칙
1. 단일 책임 원칙 Single Responsibility Principle, SRP
클래스는 단 하나의 책임만 가져야 한다.
예제
파일 읽기와 쓰기 기능을 동시에 가지는 클래스
적용 전 코드 보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
using namespace std;
class FileManager {
public:
void writeToFile(const string& filename, const string& data) const {
cout << "Writing data to file: " << filename << endl;
cout << "Data: " << data << endl;
}
string readFromFile(const string& filename) const {
cout << "Reading data from file: " << filename << endl;
return "Dummy data"; // 실제 파일 읽기 대신 가상 데이터 반환
}
};
int main() {
FileManager fileManager;
string filename = "example.txt";
string data = "Hello, SRP Example!";
// 파일 쓰기
fileManager.writeToFile(filename, data);
// 파일 읽기
string readData = fileManager.readFromFile(filename);
cout << "Read Data: " << readData << endl;
return 0;
}
파일 읽기 클래스, 파일 쓰기 클래스로 분리
적용 후 코드 보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
using namespace std;
// 파일 쓰기 클래스
class FileWriter {
public:
void writeToFile(const string& filename, const string& data) const {
cout << "Writing data to file: " << filename << endl;
cout << "Data: " << data << endl;
}
};
// 파일 읽기 클래스
class FileReader {
public:
string readFromFile(const string& filename) const {
cout << "Reading data from file: " << filename << endl;
return "Dummy data"; // 실제 파일 읽기 대신 가상 데이터 반환
}
};
int main() {
FileWriter writer;
FileReader reader;
string filename = "example.txt";
string data = "Hello, SRP Example!";
// 파일 쓰기
writer.writeToFile(filename, data);
// 파일 읽기
string readData = reader.readFromFile(filename);
cout << "Read Data: " << readData << endl;
return 0;
}