ที่นี่เราจะดูว่าคลาสพร็อกซีใน C ++ คืออะไร คลาส Proxy นั้นคือรูปแบบการออกแบบ Proxy ในรูปแบบนี้ ออบเจ็กต์จัดเตรียมอินเทอร์เฟซที่แก้ไขสำหรับคลาสอื่น เรามาดูตัวอย่างกัน
ในตัวอย่างนี้ เราต้องการสร้างคลาสอาร์เรย์ที่สามารถเก็บเฉพาะค่าไบนารี [0, 1] นี่เป็นครั้งแรกที่ลอง
โค้ดตัวอย่าง
class BinArray {
int arr[10];
int & operator[](int i) {
//Put some code here
}
}; ในรหัสนี้ไม่มีการตรวจสอบเงื่อนไข แต่เราต้องการให้โอเปอเรเตอร์[]บ่นถ้าเราใส่บางอย่างเช่น 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