4.设计模式-代理模式

定义:为其他对象提供一种代理以控制对这个对象的访问

需求

卓贾易通过戴励追女朋友娇娇。

需求分析

  • 追求者追女朋友的方法在代理对象运行
  • 被追求者知道是追求者在追

代码

相关类

c 复制代码
typedef struct SchoolGirl {
    char *name;
} SchoolGirl;

typedef struct PursuitInter {
    void (*giveDoll)(void *p);
    void (*giveFlower)(void *p);
    void (*giveChocolate)(void *p);
} PursuitInter;

被代理类

c 复制代码
typedef struct Pursuit
{
    char *name;
    SchoolGirl *girl;
    PursuitInter methods;
} Pursuit;
void PursuitGiveDoll(void *mthis) {
    printf("%s 送你洋娃娃\n", ((Pursuit *)mthis)->girl->name);
}
void PursuitGiveFlower(void *mthis) {
    printf("%s 送你花\n", ((Pursuit *)mthis)->girl->name);
}
void PursuitGiveChocolate(void *mthis) {
    printf("%s 送你巧克力\n", ((Pursuit *)mthis)->girl->name);
}
Pursuit *ConstructPursuit(char *name, SchoolGirl *girl) {
    Pursuit *obj = (Pursuit *)malloc(sizeof(Pursuit));
    obj->girl = girl;
    obj->name = name;
    obj->methods.giveDoll = PursuitGiveDoll;
    obj->methods.giveFlower = PursuitGiveFlower;
    obj->methods.giveChocolate = PursuitGiveChocolate;
    return obj;
}

代理类

c 复制代码
typedef struct Proxy {
    char *name;
    Pursuit *p;
    PursuitInter methods;
} Proxy;
void PursuitGiveChocolate(void *mthis) {
    printf("%s 送你巧克力\n", ((Pursuit *)mthis)->girl->name);
}
void ProxyGiveDoll(void *mthis) {
    ((Proxy *)mthis)->p->methods.giveDoll(((Proxy *)mthis)->p);
}
void ProxyGiveFlower(void *mthis) {
    ((Proxy *)mthis)->p->methods.giveFlower(((Proxy *)mthis)->p);
}
void ProxyGiveChocolate(void *mthis) {
    ((Proxy *)mthis)->p->methods.giveChocolate(((Proxy *)mthis)->p);
}
Proxy *ConstructProxy(char *name, char *pursuitName, SchoolGirl *girl) {
    Proxy *obj = (Proxy *)malloc(sizeof(Proxy));
    obj->name = name;
    obj->p = ConstructPursuit(pursuitName, girl);
    obj->methods.giveDoll = ProxyGiveDoll;
    obj->methods.giveFlower = ProxyGiveFlower;
    obj->methods.giveChocolate = ProxyGiveChocolate;
    return obj;
}

客户使用

c 复制代码
int main() {
    SchoolGirl jiaojiao;
    jiaojiao.name = "jiaojiao";
    Proxy *daili = ConstructProxy("daili", "zhuojiayi", &jiaojiao);
    daili->methods.giveDoll(daili);
    daili->methods.giveFlower(daili);
    daili->methods.giveChocolate(daili);
    return 0;
}

UML图

总结

  • 使用场景有哪些?
  1. 远程代理,也就是为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在不同地址空间的事实
  2. 虚拟代理,是根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的真实对象
  3. 安全代理,用来控制真实对象访问时的权限
  4. 智能指引,是指当调用真实的对象时,代理处理另外一些事
相关推荐
青禾网络2 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO3 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯3 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术3 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉4 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯5 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆7 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813397 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫8 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构