Praktische Muster – Commands
- Januar 22nd, 2010
- Posted in CSharp . Development
- Kommentar schreiben
Ein schönes Beispiel für ein praktisches Entwurfsmuster habe ich im Archiv der dot.net gefunden.
In der Ausgabe 1/2009 beschreibt Marc André Zhou mit einem einfachen Beispiel, wie man ein Muster für Commands implementiert.
Hierzu definiert er ein Interface ICommand, welches die Methode Execute() festlegt.
1 2 3 4 | public interface ICommand { void Execute(); } |
Die Klassen, die das Interface implementieren, öffnen jeweils eine Applikation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class CMDNotepad : ICommand { public void Execute() { Process process = new Process(); process.StartInfo = new ProcessStartInfo(@"notepad.exe"); process.Start(); } public override string ToString() { return "notepad.exe"; } } |
Im MainProgramm dann, werden die einzelnen Commands einer Liste vom Typ ICommand hinzugefügt
1 2 3 4 | var commands = new List<ICommand>(); commands.Add(new CMDNotepad()); commands.Add(new CMDIExplorer()); commands.Add(new CMDCalc()); |
und anschliessend ausgegeben.
1 2 3 4 5 | foreach (ICommand cmd in commands) { Console.WriteLine("Start command: {0}", cmd); cmd.Execute(); } |
Ich finde das Beispiel auch als eine sehr gute Erklärung, wie ein Interface arbeitet und an welcher Stelle man eins einsetzen sollte.
Viel Spass beim entwickeln : )
Ähnliche Beiträge
Auch wenn Du nichts zu diesem Thema sagen möchtest, bringst du mit einem Klick auf den Like- oder KickButton zum Ausdruck, dass dir dieser Artikel gefällt. Vielen Dank : )




Noch keine Kommentare.