এখানে আমরা C++-এ প্রক্সি ক্লাস (Proxy Class) কী তা দেখব। প্রক্সি ক্লাস মূলত প্রক্সি ডিজাইন প্যাটার্ন (Proxy design pattern)। এই প্যাটার্নে একটি অবজেক্ট অন্য একটি ক্লাসের জন্য মডিফাইড ইন্টারফেস প্রদান করে। একটি উদাহরণ দেখি।
এই উদাহরণে, আমরা একটি অ্যারে ক্লাস তৈরি করতে চাই যা শুধু বাইনারি ভ্যালু [0, 1] স্টোর করবে। এটি প্রথম চেষ্টা।
উদাহরণ কোড (প্রথম চেষ্টা - সমস্যা আছে)
class BinArray {
int arr[10];
int& operator[](int i) {
// এখানে কিছু কোড হবে
}
};
এই কোডে কোনো কন্ডিশন চেকিং নেই। কিন্তু আমরা চাই 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; // এক্সসেপশন নেই
cout << a.item_at_pos(0) << endl;
}
catch (const char* e) {
cout << e << endl;
}
try {
a[1] = 98; // এক্সসেপশন থ্রো করবে
cout << a.item_at_pos(1) << endl;
}
catch (const char* e) {
cout << e << endl;
}
}
আউটপুট
1 This is not a binary digit