Archive for the ‘ Behavioral Patterns ’ Category

The Observer Pattern

ObserverToday I would like to present the Observer pattern from the familiy of the behavioral patterns to you. From my point of view it is one of the most important and most used patterns and should be part of the basic knowledge of every good programmer. Some of you may want to say : “Hey why do you spent time in writing this ? Java and .NET have delegates and events so you most commonly don’t have to implement observers on your own.” You are right ! But I think it is very important to understand the technology behind it and so I want to give the beginners of you a crash course.

To warm up a little, let’s do a small example:
Let’s imagine we are sitting at a controlpanel and our job is to supervise the location of some trains. That would be an enourmous work to always ask the trains for their location, wouldn’t it ? So why don’t we turn the tides ? Let the train do the job and let him notify us if his location has changed. All we have to do is to tell him that they should notify us in time. The Advantage with that is, that the train is able to notify not just you but also everyone who has told him to do so. So all of your teammates are able to get the train’s position, too.

Read the rest of this entry »

Das Strategy Pattern

Strategy pic Das Strategy Pattern, auch “Policy Pattern” gennant, ist eines der Behavorial Patterns der GoF. Es beschreibt eine Möglichkeit, verschiedene Algorithmen zur Laufzeit festzulegen oder sogar zu wechseln. Die Algorithmen werden dazu in verschiedenen Klassen gekapselt und erst zur Laufzeit instantiiert. Um eine allgemeine Zugriffsschnittstelle zu haben, werden diese “Konkreten Strategy’s” von einer Oberklasse abgeleitet.

Wann aber setze ich das Strategy Pattern überhaupt ein ?
Nun z.B. dann wenn verschiedene Objekte existieren die sich nur durch ihr Verhalten unterscheiden. Anwendungsbeispiele wären z.b. Türen. Es gibt eine ganz Menge unterschiedlicher Türen. Haustür, Garagentor, Autotür, Flugzeugtür, Safetür. Alle besitzen z.B. eine Methode Open(), aber alle funktionieren auf unterschiedliche Art und Weise. Die eine muss man aufziehen, bei der anderen die Klinke runterdrücken und wieder bei der anderen erst einen Code knacken. Die konkrete Implementierung findet in der jeweiligen Türklasse selbst statt.

Ein einfaches Beispiel :
Wir versuchen das Türbeispiel zu implementieren. Dazu benötigen wir eine Basisklasse die eine Tür beschreibt.

Klasse einer Tuer

Und ein paar konkrete Türen die wir in unserem Beispiel verwenden werden. Diese Erben von der Basistürklasse.

Strategy Beispiel Tür

Read the rest of this entry »