Entwickler-Ecke

Sonstiges (.NET) - C# Design Pattern: Decorator


meisse - Mo 18.10.10 21:41
Titel: C# Design Pattern: Decorator
Hallo zusammen

Habe versucht das Design Pattern "Decorator" zu bauen. Habe dabei folgendes Beispiel gemacht. Könnt ihr mir
sagen ob dies so ok ist oder ob man das Pattern in meinem Beispiel noch anders machen muss. Das ganze macht
noch nicht wirklich viel, aber soll das Gerüst für einen Decorator darstellen:


C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
namespace MyDecorator {
    public partial class Photo : Form, IPhoto {
        public Photo() {
            Paint += new PaintEventHandler(Drawer);
        }

        public void Drawer(Object source, PaintEventArgs e) {
            Debug.WriteLine("Paint Form1.cs");
        }
    }
}

---------------------------------------------------------------------

namespace MyDecorator {
    class Decorator : Form, IPhoto  {
        IPhoto photo;
        string text;

        public Decorator(IPhoto photo, string text) : base() {
            this.photo = photo;
            this.text = text;
            Paint += new PaintEventHandler(Drawer);
        }

        public void Drawer(Object source, PaintEventArgs e) {
            photo.Drawer(source, e);
            Debug.WriteLine("Paint Decorator.cs");
        }
    }
}

---------------------------------------------------------------------

namespace MyDecorator {
    interface IPhoto {
        void Drawer(Object source, PaintEventArgs e);
    }
}

---------------------------------------------------------------------

namespace MyDecorator {
    static class Program {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Photo obj = new Photo();
            Decorator dec = new Decorator(obj, "test");
            Application.Run(dec);
        }
    }
}


Mit freundlichen Grüssen


Th69 - Di 19.10.10 11:44

Hallo,

mir sieht dein Beispiel nicht nach dem "Decorator"-Pattern aus, denn dein "Decorator" soll doch das "Photo" umhüllen. Beide sind aber eigenständige Form-Instanzen, d.h. die Decorator-Form hat nichts mit der Photo-Form gemeinsam (du müsstest so jede Eigenschaft, Methode und Ereignis an die andere Form weiterreichen!!!).
Normalerweise verwendet man abstrakte Klassen zur Dekoration.

Schau dir mal das C#-Beispiel auf http://de.wikipedia.org/wiki/Decorator an...

Wofür brauchst du denn den "Decorator"?