使用思路:需要某类需要添加新的处理方式,但是不修改类
初始类
// The original Photo class
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);
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Photo
//
this.ClientSize = new System.Drawing.Size(283, 250);
this.Name = "Photo";
this.ResumeLayout(false);
}
在一些情况需要扩展,但又不想改源代码。那就看下面是怎么扩展的:
// This simple BorderedPhoto decorator adds a colored BorderedPhoto of fixed size
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);
}
}
集成了原来的类,重新处理了一下图片的边框显示。
这样单纯显示图片就用原来的类,需要添加边框的时候则可以选用这个BorderedPhoto类来处理图片。
前面的掩饰简单描述了装饰其模式。此模式描述应该就算结束了。
--------------------------------以下可忽略------------------------------------
高级应用则需要深入研究:
// The TaggedPhoto decorator keeps track of the tag number which gives it
// a specific place to be written
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 () {
// Application.Run acts as a simple client
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());
}
显示原始图片
第一个,字符foodTaggedPhoto放入了原始类进行处理,结果应该是原始图片加入food字符
第二个,字符colorTaggedPhoto放入了前一个带food字符的图片,再加入了yellow字符
第三个,边框composition 放入了前一个带food,yellow的图片,再加入了蓝色边框
显示第三张图(带food,yellow,蓝色边框)
第二次处理
再次初始化原始图片
第一个,字符tag放入原始类进行处理,结果加入jug字符
第二个,边框composition 放入前一个jug图片,家黄色边框
显示第二张图片(带jug,黄色边框)