Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

design patterns - What is Proxy Class in C++

What is a Proxy Class in C++? Why it is created and where it is useful?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A proxy is a class that provides a modified interface to another class.

Here is an example - suppose we have an array class that we only want to contain binary digits (1 or 0). Here is a first try:

struct array1 {
    int mArray[10];
    int & operator[](int i) {
      /// what to put here
    }
}; `

We want operator[] to throw if we say something like a[1] = 42, but that isn't possible because that operator only sees the index of the array, not the value being stored.

We can solve this using a proxy:

#include <iostream>
using namespace std;

struct aproxy {
    aproxy(int& r) : mPtr(&r) {}
    void operator = (int n) {
        if (n > 1 || n < 0) {
            throw "not binary digit";
        }
        *mPtr = n;
    }
    int * mPtr;
};

struct array {
    int mArray[10];
    aproxy operator[](int i) {
        return aproxy(mArray[i]);
    }
};

int main() {
    try {
        array a;
        a[0] = 1;   // ok
        a[0] = 42;  // throws exception
    }
    catch (const char * e) {
        cout << e << endl;
    }
}

The proxy class now does our checking for a binary digit and we make the array's operator[] return an instance of the proxy which has limited access to the array's internals.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...