一、装饰模式
用户使用代码:
//基类
class Subject
{
public:
virtual void operation();
};
//具体类
class ConcreteSubject : public Subject
{
public:
virtual void operation();
};
//装饰类
class Decorate : public Subject
{
public:
Decorate(Subject* pSubject);
virtual void operate();
private:
Subject* m_pSubject;
};
//具体装饰类
class ConcreteDecorate : public Decorate
{
public:
ConcreteDecorate(Subject* pSubject);
virtual void operate();
};
ConcreteDecorate(Subject* pSubject)
:Decorate(pSubject)
{
}
void ConcreDecorate::operate()
{
//other operation
//otheroperate();
super.operate();
}
int main()
{
Subject* pSubject = new ConcreteSubject();
Decorate* pDecorate = new ConcreteDecorate(pSubject);
pDecorate->operation();
return 0;
}
二、代理模式
代码示例:
//基类
class Subject
{
public:
virtual void operation();
};
//具体类
class ConcreteSubject : public Subject
{
public:
virtual void operation();
};
//代理类
class Proxy : public Subject
{
public:
virtual void operation();
private:
ConcreteSubject m_objConcreteSubject;
};
void Proxy::operation()
{
m_objConcreteSubject.operation();
}
int main()
{
Subject* pSubject = new Proxy();
pSubject->operation();
}
三、对比
从类图关系来看,装饰模式中由Decorate类聚合Subject类,用户使用时,需要自己构造Subject实例,然后将Subject实例作为Decorate构造函数参数传入Decorate,Decorate实例在实现具体操作时,除了调用Subject的操作函数还添加补充操作函数,起到“装饰”的作用。代理模式中Proxy类负责Subject实例的构造和销毁,用户在使用过程中不用直接操作Subject具体实例,由Proxy来负责实现具体的操作。
装饰模式主要强调对Subject类功能的扩展,而代理模式侧重于对Subject类的访问控制。