以下是一个简单的 C 语言代理模式示例:
#include
// 真实主题(Real Subject)
typedef struct {
int value;
} RealSubject;
void RealSubject_init(RealSubject *self) {
self->value = 0;
}
void RealSubject_setValue(RealSubject *self, int value) {
self->value = value;
}
int RealSubject_getValue(RealSubject *self) {
return self->value;
}
// 代理(Proxy)
typedef struct {
RealSubject real_subject;
} Proxy;
void Proxy_init(Proxy *self) {
RealSubject_init(&self->real_subject);
}
void Proxy_setValue(Proxy *self, int value) {
RealSubject_setValue(&self->real_subject, value);
}
int Proxy_getValue(Proxy *self) {
return RealSubject_getValue(&self->real_subject);
}
int main() {
Proxy proxy;
Proxy_init(&proxy);
Proxy_setValue(&proxy, 42);
printf("Value: %d
", Proxy_getValue(&proxy));
return 0;
}
在上面的示例中,我们有一个真实主题 RealSubject
,它有一个整数值,可以设置和获取。我们还有一个代理 Proxy
,它包装了真实主题,提供相同的设置和获取方法。
当我们对代理调用 setValue
时,代理将调用真实主题的 setValue
方法。当我们对代理调用 getValue
时,代理将调用真实主题的 getValue
方法,并返回该方法的结果。
在这个示例中,代理模式的好处在于我们可以在不修改真实主题的代码的情况下,通过代理来控制对真实主题的访问。例如,我们可以在代理中添加一些验证或日志记录,而不必修改真实主题的代码。