代理模式

1.引言

这两天一直在看Openstack的ceilometer模块,它的官方文档里有这么一段话:

Polling:

The Telemetry service is intended to store a complex picture of the infrastructure. This goal requires additional information than what is provided by the events and notifications published by each service. Some information is not emitted directly, like resource usage of the VM instances.

Therefore Telemetry uses another method to gather this data by polling the infrastructure including the APIs of the different OpenStack services and other assets, like hypervisors. The latter case requires closer interaction with the compute hosts. To solve this issue, Telemetry uses an agent based architecture to fulfill the requirements against the data collection.

大概意思就是说,Telemetry服务目的是存储一张关于基础架构的大图,这个实现除了依赖被每个系统发出来的事件和通知外,还有依赖一些不能主动发出来的数据,例如vm实例的使用率。

因此Telemetry服务采用轮训机制去查询openstack其他服务的状态和其他资源(比如 hypervisors),查询hypervisors信息时会与硬件资源密切交换,所以就使用了代理模式。

我当时不解,为什么是代理模式不是其他模式,代理模式有什么好处,代理模式怎么实现的?

2. 代理模式

官方解释:给某一个对象提供一个代理或占位符,并由代理对象来控制对原对象的访问。 

简而言之,就是转发嘛。为了翻墙,我们也没少使用代理模式。

3. 代理模式的结构

4. 代理模式的实现

采用大话设计模式里的例子,一个程序员追求一个妹子,但是他不敢去,找了一个朋友帮忙送花、送吃的、讲笑话。

定义一个追求着接口:

class IPersuer
{
public:
    virtual void SendFlower() = 0;
    virtual void SendFood() = 0;
    virtual void TellJoker() = 0;
};

然后再定义一个这个程序员类,实现这个接口:

class Persuer : public IPersuer
{
public:
    void SendFlower()
    {
        printf("Send Flower
");
    }


    void SendFood()
    {
        printf("Send Food
");
    }

    void TellJoker()
    {
        printf("Tell Joker
");
    }
};

但是他不敢去,只能找朋友帮忙,这个朋友就是个代理:

class Proxy : public IPersuer
{
private:
    IPersuer* persuer_;
public:
    void SetPersuer(IPersuer* persuer)
    {
        persuer_ = persuer;
    }

    void SendFlower()
    {
        persuer_->SendFlower();
    }

    void SendFood()
    {
        persuer_->SendFood();
    }

    void TellJoker()
    {
        persuer_->TellJoker();
    }
};

最后由代理去帮程序员追妹子:

void TestProxy()
{
    Proxy proxy;
    Persuer persuer;
    proxy.SetPersuer(&persuer);

    proxy.SendFlower();
    proxy.SendFood();
    proxy.TellJoker();
}

5. 代理模式有什么好处

由上面的例子可知:

1、不方便自己出手的,找个代理,这样就能减少自己与女孩子的接触,这就起了隔离保护目标的作用,这也就是为什么Telemetry使用代理模式了。

2、其实代理模式还有一个优点,高拓展性,这里是动态代理特性,待以后研究。

原文地址:https://www.cnblogs.com/alvin2010/p/8876123.html