여기서 우리는 C++에서 프록시 클래스가 무엇인지 볼 것입니다. Proxy 클래스는 기본적으로 Proxy 디자인 패턴입니다. 이 패턴에서 객체는 다른 클래스에 대해 수정된 인터페이스를 제공합니다. 한 가지 예를 살펴보겠습니다.
이 예제에서는 이진 값 [0, 1]만 저장할 수 있는 배열 클래스를 만들고 싶습니다. 첫 시도입니다.
예시 코드
class BinArray {
int arr[10];
int & operator[](int i) {
//Put some code here
}
}; 이 코드에서는 조건 검사가 없습니다. 그러나 우리는 operator[]가 arr[1] =98과 같은 것을 넣으면 불평하기를 원합니다. 그러나 이것은 값이 아닌 인덱스를 확인하기 때문에 불가능합니다. 이제 프록시 패턴을 사용하여 이 문제를 해결해 보겠습니다.
예시 코드
#include <iostream>
using namespace std;
class ProxyPat {
private:
int * my_ptr;
public:
ProxyPat(int& r) : my_ptr(&r) {
}
void operator = (int n) {
if (n > 1) {
throw "This is not a binary digit";
}
*my_ptr = n;
}
};
class BinaryArray {
private:
int binArray[10];
public:
ProxyPat operator[](int i) {
return ProxyPat(binArray[i]);
}
int item_at_pos(int i) {
return binArray[i];
}
};
int main() {
BinaryArray a;
try {
a[0] = 1; // No exception
cout << a.item_at_pos(0) << endl;
}
catch (const char * e) {
cout << e << endl;
}
try {
a[1] = 98; // Throws exception
cout << a.item_at_pos(1) << endl;
}
catch (const char * e) {
cout << e << endl;
}
} 출력
1 This is not a binary digit