Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Proxy Class ใน C++ คืออะไร

Proxy class คือ Proxy design pattern ออบเจ็กต์หนึ่งให้ interface ที่ปรับแต่งแล้วสำหรับอีกคลาสหนึ่ง มาดูตัวอย่าง

เราต้องการสร้างคลาสอาร์เรย์ที่เก็บค่า binary [0,1] เท่านั้น ลองครั้งแรก:

class BinArray {
    int arr[10];
    int& operator[](int i) {
        // ไม่มีการตรวจสอบค่า
    }
};

โค้ดนี้ไม่ตรวจสอบค่า เราต้องการให้ operator[] แจ้งเตือนถ้า arr[1] = 98 แต่ไม่ได้เพราะตรวจดัชนี ไม่ใช่ค่า ใช้ proxy pattern แก้

ตัวอย่าง Proxy Pattern

#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; // ไม่มี exception
        cout << a.item_at_pos(0) << endl;
    } catch (const char* e) {
        cout << e << endl;
    }
    try {
        a[1] = 98; // โยน exception
        cout << a.item_at_pos(1) << endl;
    } catch (const char* e) {
        cout << e << endl;
    }
}

ผลลัพธ์

1
This is not a binary digit