设计模式读书笔记:装饰器模式

  

     “装饰器”,顾名思义 就是在一个现有的对象上附加新的东西。作为例子,可以考虑在屏幕上显示一张图片。在图片上附加新东西有多种方式,比如加上一个边框,或者打上

一个跟图片内容有关的标签。

     装饰器模式的美妙之处在于:

       1 原始对象对装饰一无所知;

       2 不需要引入一个包含各种装饰选项的特性类;

       3 多个装饰类之间彼此独立;

       4 多个装饰类可以以一种“混搭”的方式组合到一起。

   示例代码:

1 using System;
2 using System.Drawing;
3 using System.Drawing.Drawing2D;
4 using System.Windows.Forms;
5 using System.Collections.Generic;
6 using Given;
7
8
9
10 namespace Given {
11
12 public class Photo : Form {
13 Image image;
14 public Photo () {
15 image = new Bitmap("jug.jpg");
16 this.Text = "Lemonade";
17 this.Paint += new PaintEventHandler(Drawer);
18 }
19
20 public virtual void Drawer(Object source, PaintEventArgs e) {
21 e.Graphics.DrawImage(image,30,20);
22 }
23 }
24 }
25
26 class DecoratorPatternExample {
27
28 class BorderedPhoto : Photo {
29 Photo photo;
30 Color color;
31
32 public BorderedPhoto (Photo p, Color c) {
33 photo = p;
34 color=c;
35 }
36
37 public override void Drawer(Object source, PaintEventArgs e) {
38 photo.Drawer(source, e);
39 e.Graphics.DrawRectangle(new Pen(color, 10),25,15,215,225);
40 }
41 }
42
43
44 class TaggedPhoto : Photo {
45 Photo photo;
46 string tag;
47 int number;
48 static int count;
49 List <string> tags = new List <string> ();
50
51 public TaggedPhoto(Photo p, string t) {
52 photo = p;
53 tag = t;
54 tags.Add(t);
55 number = ++count;
56 }
57
58 public override void Drawer(Object source, PaintEventArgs e) {
59 photo.Drawer(source,e);
60 e.Graphics.DrawString(tag,
61 new Font("Arial", 16),
62 new SolidBrush(Color.Black),
63 new PointF(80,100+number*20));
64 }
65
66 public string ListTaggedPhotos() {
67 string s = "Tags are: ";
68 foreach (string t in tags) s +=t+" ";
69 return s;
70 }
71 }
72
73
74
75 static void Main () {
76 Photo photo;
77 TaggedPhoto foodTaggedPhoto, colorTaggedPhoto, tag;
78 BorderedPhoto composition;
79
80 // Compose a photo with two TaggedPhotos and a blue BorderedPhoto
81   photo = new Photo();
82 Application.Run(photo);
83 foodTaggedPhoto = new TaggedPhoto (photo,"Food");
84 colorTaggedPhoto = new TaggedPhoto (foodTaggedPhoto,"Yellow");
85 composition = new BorderedPhoto(colorTaggedPhoto, Color.Blue);
86 Application.Run(composition);
87 Console.WriteLine(colorTaggedPhoto.ListTaggedPhotos());
88
89 // Compose a photo with one TaggedPhoto and a yellow BorderedPhoto
90   photo = new Photo();
91 tag = new TaggedPhoto (photo,"Jug");
92 composition = new BorderedPhoto(tag, Color.Yellow);
93 Application.Run(composition);
94 Console.WriteLine(tag.ListTaggedPhotos());
95 }
96 }
posted @ 2011-07-11 14:32  zrj531  阅读(979)  评论(0编辑  收藏  举报