设计模式读书笔记:装饰器模式
2011-07-11 14:32
225 查看
“装饰器”,顾名思义 就是在一个现有的对象上附加新的东西。作为例子,可以考虑在屏幕上显示一张图片。在图片上附加新东西有多种方式,比如加上一个边框,或者打上
一个跟图片内容有关的标签。
装饰器模式的美妙之处在于:
1 原始对象对装饰一无所知;
2 不需要引入一个包含各种装饰选项的特性类;
3 多个装饰类之间彼此独立;
4 多个装饰类可以以一种“混搭”的方式组合到一起。
示例代码:
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections.Generic; using Given; namespace Given { public class Photo : Form { Image image; public Photo () { image = new Bitmap("jug.jpg"); this.Text = "Lemonade"; this.Paint += new PaintEventHandler(Drawer); } public virtual void Drawer(Object source, PaintEventArgs e) { e.Graphics.DrawImage(image,30,20); } } } class DecoratorPatternExample { class BorderedPhoto : Photo { Photo photo; Color color; public BorderedPhoto (Photo p, Color c) { photo = p; color=c; } public override void Drawer(Object source, PaintEventArgs e) { photo.Drawer(source, e); e.Graphics.DrawRectangle(new Pen(color, 10),25,15,215,225); } } class TaggedPhoto : Photo { Photo photo; string tag; int number; static int count; List <string> tags = new List <string> (); public TaggedPhoto(Photo p, string t) { photo = p; tag = t; tags.Add(t); number = ++count; } public override void Drawer(Object source, PaintEventArgs e) { photo.Drawer(source,e); e.Graphics.DrawString(tag, new Font("Arial", 16), new SolidBrush(Color.Black), new PointF(80,100+number*20)); } public string ListTaggedPhotos() { string s = "Tags are: "; foreach (string t in tags) s +=t+" "; return s; } } static void Main () { Photo photo; TaggedPhoto foodTaggedPhoto, colorTaggedPhoto, tag; BorderedPhoto composition; // Compose a photo with two TaggedPhotos and a blue BorderedPhoto photo = new Photo(); Application.Run(photo); foodTaggedPhoto = new TaggedPhoto (photo,"Food"); colorTaggedPhoto = new TaggedPhoto (foodTaggedPhoto,"Yellow"); composition = new BorderedPhoto(colorTaggedPhoto, Color.Blue); Application.Run(composition); Console.WriteLine(colorTaggedPhoto.ListTaggedPhotos()); // Compose a photo with one TaggedPhoto and a yellow BorderedPhoto photo = new Photo(); tag = new TaggedPhoto (photo,"Jug"); composition = new BorderedPhoto(tag, Color.Yellow); Application.Run(composition); Console.WriteLine(tag.ListTaggedPhotos()); } }
相关文章推荐
- 读书笔记_java设计模式深入研究 第十一章 装饰器模式 Decorator
- 设计模式读书笔记之装饰器模式(Decorator)
- 设计模式读书笔记[3]:装饰模式(Decorator)
- 设计模式读书笔记:Decorator(装饰)
- 设计模式读书笔记之装饰器模式(Decorator)
- 代理模式、装饰模式、适配器模式、组合模式、桥梁模式、外观模式、享元模式【读书笔记】设计模式4章:结构型模式
- 15读书笔记之装饰着设计模式
- Java IO学习【10】装饰设计模式
- 设计模式读书笔记[4]:命令模式(Command)
- IOS设计模式之二(门面模式,装饰器模式)
- 设计模式-----装饰模式
- 设计模式(一)——装饰设计模式
- 设计模式阅读备忘笔记-装饰模式
- 设计模式-----装饰模式.
- java设计模式——装饰模式
- 设计模式-装饰模式
- C#设计模式之八装饰模式(Decorator Pattern)【结构型】
- 装饰设计模式
- [设计模式][装饰模式][Javascript]
- 设计模式读书笔记之原型模式(Prototype)