笔记:Gof设计模式--Decorator
来源:互联网 发布:oracle数据库创建索引 编辑:程序博客网 时间:2024/06/10 04:36
1、意图
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
2、适应性
Use the Decorator pattern when
• to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
• for responsibilities that can be withdrawn.
• when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.
3、结构
4、示例代码
The following code shows how to implement user interface decorators in C++. We'll assume there's a Component class called VisualComponent And subclass Decorator.
class VisualComponent { public: VisualComponent(); virtual void Draw(); virtual void Resize(); // ... };
class Decorator : public VisualComponent { public: Decorator(VisualComponent*); virtual void Draw(); virtual void Resize(); // ... private: VisualComponent* _component; };
For each operation in VisualComponent's interface, Decorator defines a default implementation that passes the request on to _component:
void Decorator::Draw () { _component->Draw(); } void Decorator::Resize () { _component->Resize(); }
the class BorderDecorator adds a border to its enclosing component.
class BorderDecorator : public Decorator { public: BorderDecorator(VisualComponent*, int borderWidth); virtual void Draw(); private: void DrawBorder(int); private: int _width; }; void BorderDecorator::Draw () { Decorator::Draw(); DrawBorder(_width); }
we want a bordered and scrollable TextView. So we decorate it accordingly before putting it in the window. We'll assume our Window class provides a SetContents operation for this purpose:
void Window::SetContents (VisualComponent* contents) { // ... } window->SetContents( new BorderDecorator( new ScrollDecorator(textView), 1 ) );
- 笔记:Gof设计模式--Decorator
- 读GOF设计模式杂记之 Decorator
- GOF设计模式之DECORATOR(装饰)
- Decorator装饰者模式 - GoF设计模式(二)
- GOF 23设计模式之 装饰模式(Decorator)
- 笔记:Gof设计模式--Builder
- 笔记:Gof设计模式--Prototype
- 笔记:Gof设计模式--Singleton
- 笔记:Gof设计模式--Adapter
- 笔记:Gof设计模式--Bridge
- 笔记:Gof设计模式--Composite
- 笔记:Gof设计模式--Flyweight
- 笔记:Gof设计模式--Proxy
- 笔记:Gof设计模式--Command
- 笔记:Gof设计模式--Iterator
- 笔记:Gof设计模式--Mediator
- 笔记:Gof设计模式--Memento
- 笔记:Gof设计模式--Observer
- 读高质量c/c++编程之内存管理笔记1
- Junit4 新断言语法介绍(转)
- UVa 340 - Master-Mind Hints
- C语言开发之关于sprintf 你知道多少
- 这关又没过去
- 笔记:Gof设计模式--Decorator
- postgresql常用命令
- sohu2012年实习生笔试题
- 比较好的android博客
- CountDownLatch 控制多线程 让多个线程执行完后再依次做其他的
- 从linux平台移值数据库到windows平台
- C++中类的理解
- 产品经理常犯的七大错误
- ServletResponse的刷新头和禁止浏览器缓存头的使用