Design Patterns #2: Observer

Dzień dobry!
Continuing on design patterns – it’s time for the Observer. This pattern allows linkage between one observable and many observers that when the observable changes its states the observers are automatically notified and updated. So, the observable has a collection of observers, it performs its actions and when certain defined event happens it notifies its own observers. Let’s take a look at the diagram:


Let’s start with the observers: their interface defines only one method: Update(). That method returns void and can take parameters. In fact parameters are used to notify the actual change and not only the fact that the value has changed. It will be later shown in the example.
Now the observable: it must have possibility to add and remove observers (Register() and Unregister() methods respectively, as an argument they take  object that implements IObserver interface) and to notify its observers about the change. Concrete implementation of the observable also has some sort of observers collection. (This collection is not part of the interface because a) it doesn’t have to be public, b) methods to register and unregister the observers are exposed publicly and that’s enough for the client, it doesn’t have to know how references to the observers are stored. Of course it doesn’t have to be like that. What we’re discussing here is just the pattern and its actual implementation may vary depending on every particular need.) Usual implementation of Notify() is iteration through the observers collection and invoking Update() method on each of them. And that’s it. Let’s go with the example.

EXAMPLE
Example given in the book (previous post explains what book) is a weather station (measures temperature, pressure etc.)  and several types of display (current conditions, stats etc.) I think that’s a really good example but our example will be simpler but similar to some extent. We’re going to build number generator and two types of display.

Interfaces
Have a quick look at the code below:

Hey, where’s Notify() method?! We don’t want that method to be exposed publicly therefore it won’t be here in the interface. As said earlier, the design patterns are not exact implementation nor have strict code structure, they are more of a general ways to achieve some result. But if you hear from another developer that he has used the observer pattern (or any other pattern) you will instantaneously know what to expect.
IObserver interface defines only one method which is Update() that takes one integer parameter which will be passed to our observers.

Concretions – Number Generator

Our number generator will – surprise, surprise – generate random numbers within given range (which is specified by constructor’s parameters). It has list of objects of type IObserver and two methods that allow adding and removing from that list. Method notify() is private as we don’t want to make it possible from the outside of the class to force the observable to notify its observers. This method (as you can read above in this post) simply iterates through observers collection and invoke Update() method on each of them. This method is invoked inside Next() method which generates next random number. Parameter of the Update() method is last generated number.

Concretions – Observers

These two implementations of IObserver using their Display() method print their current readings to console. One of them displays aggregated value of all random number passed from the observable, and the other displays average value. Their Update() are consistent with the interface they implement.

Wiring all together
All the above classes will work together in this small console app.

As you can see once we have an instance of NumberGenerator we can register some observers. Our console app will iterate 10 times and draw 10 random numbers and display readings of our observers.

Self-registration/unregistration
The example above shows basic implementation of the observer pattern. It may be improved by allowing object to self-register/unregister. This can be simply done by storing reference to observable in the observer. In this case observer will need appropriate methods: to register that takes observable as an argument, and to unregister with no arguments. Let’s take a look at its interface:

It extends existing IObserver interface and adds two methods as described earlier. Now, the concretion:

So, it now has a reference to the observer which initially is null. When we want to self-register it to a particular observer we simply invoke SelfRegister() method and pass the observer as an argument. The method will save the reference to the observer and invoke observer’s Register() method with this passed as an argument. SelfUnregister() method performs opposite actions. The code says it all 🙂
Below you will find to txt file with the source code. Thanks for today, and hopefully see you next week. Cheers!

Source code: download txt file

Design Patterns #1: Strategy

Nau mai!
Time for design patterns. Whenever I tried to find out anything about them I encountered this pretty good explanation what are they and why we need them:

Someone has already solved your problems.

‘Head First Design Patterns’ (page 1)

And after Wikipedia:

In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.

[source]

In a nutshell: common solutions to common problems. And that should be sufficient to start with first design pattern: Strategy. But, before that quick introduction to this series. It is inspired by Christopher Okhravi and his playlist. I will do basically the same: go through all design patterns in Head First Design Patterns book by Eric Freeman, Elisabeth Freeman, Bert Bates and Kathy Sierra. I have Polish edition but that does not make any difference for you, I will not give any quote in Polish (probably I won’t give any quote at all). To make this series somehow different and not to copy either the book or videos linked above I will use different examples. So, with that being sad we can cut to the chase.

Definition
Strategy defines common abstraction of set of algorithms, encapsulates them and make them reusable and interchangeable in run-time.

How is that achieved:

  1. Define abstract class or interface that has one common method which invocation will perform some action
  2. Define concretions for the above
  3. Add variable of type strategy abstraction to your client class
  4. Add method in your client class which will execute strategy
  5. Add method in your client class that will allow to change strategy

    And that’s basically it. Now, let’s move to example.

    Example
    Example given in book is a duck simulator. It uses different types of duck where actions such as quack or fly are abstracted and encapsulated into strategies. Good example in my opinion. Our example is magic box that consist of an array of 10 integers which can be displayed in console. But the way the numbers are displayed varies depending on enumeration strategy. Let’s start with abstracting the enumeration strategy:

    So, our strategy is used to return string that enumerates all numbers in given array.
    Now, let’s implement different strategies: enumerate as is (without changing the order), bubble sorted and shuffled.

    What could be done better in those three implementations is that part of the code that build output string is common so natural reaction would be to encapsulate it somehow, but please, turn a blind eye for that 🙂
    Next step – writing our MagicBox class which has an array of 10 integer, randomly generated in the constructor, private field of type IEnumerateStrategy accompanied by a method for changing the strategy, and Display() method that writes numbers to the console using the strategy.

    To test the example in application’s Main() method, we will create new MagicBox object and assign new AsIsEnumeratorStrategy, then invoke Display() method, and then assign some other available strategies and again invoke Display() method.

    So, as a result we get number listed using three different strategies. Advantages of using Strategy Pattern is that you can write as many strategies as you want without changing the class that uses them and interchange them during run-time (the definition, right?).So that’s it when it comes to Strategy Pattern. If you’re interested in next pattern (which is going to be the Observer) please come back (probably) next week. Thanks!

    Source code: download zip file

User-defined value type

Hello there!
Something basic today: how to write your own value type. In C# we distinguish two kinds of data type: value type and reference type. The former is a) stored on stack, b) is by default it is passed as an argument by value; the latter is a) stored on heap and only its address is stored on stack, b) is passed as an argument by reference. At this stage the important thing that is needed to know is that point a makes impact on performance [more]; point b makes impact of how data is circulating through methods. If an argument is passed by value only the value will be taken into the method and, we may say, the link between variable name and its value will be gone from method’s point of view, this means that the original variable cannot be modified by the method. If an argument is passed by reference that link will still be valid meaning that whatever changes a method do to the data it will be reflected everywhere that data is used. The code below will make it much clearer:

The output of the above would be:
As you can see modifications to our list of strings which is a reference type have been done to our object, however our integer variable which is a value type have not changed because only its value was passed to the method. That’s the main difference. The good thing to know is that value types can also be passed by reference – to do that we use keyword ref before an argument we want to pass by reference. This keyword must be present both in method signature and in its invocation place.

And the result:
So, that explanation is enough. We know what is the difference between value and reference type and what implication does that difference bring to behaviour of these types. Now, let’s move on to our custom value type. These are basically structs. They (similarly to classes) can consist of fields, properties, methods etc. and struct’s members can be static, but the struct itself cannot be static. Another important feature is that a struct cannon be derived from a class (that’s obvious) or another struct, however they can implement interfaces.

Our value type will store coordinates assuming that point 0,0 is the bottom left corner of our plane – this means that only positive values of component X and component Y can be assigned. This is due to way of how our value type will be assigned:

So, let’s start with required properties for X and Y coordinates, and distance from point 0,0. That’s simple:

Now, time for constructor. What it is actually going to do is decomposition into two coordinate component. It is also going to be private as we won’t be creating variables of this type using the constructor but simply by assigning a double.

This decomposition is achieved by using some of the static methods of Math class [see here].

Now, the fun part: how to make it possible to assign double value to our struct using ‘=’ operator? Simply by defining new implicit conversion operator that will use already defined private constructor to create an instance of our struct.

Next step would be to override three methods: ToString(), GetHashCode() and Equals() methods. A word of explanation here: although a struct is a value type it is derived from ValueType type, which in turn is derived from Object, and despite the fact that it is not necessary to override those three methods we want to be sure that they will act as we intend: ToString() will return X and Y components separated by comma, GetHashCode() will return hash code for double created based on X and Y, and Equals will check if the argument is of our user-defined type and if it does the method will compare X components and Y components:

And now we’re at the point where we could stop. Having the above done is enough to use our struct but we want to override some of the operators to make it easier to use. We will override pair ‘==’ and ‘!=’, and ‘+’ and ‘-‘ operators. For the comparison operators we assume that our structs are equal if both counterparting components are equal, for addition and subtraction we will add or subtract components X and Y:

And that’s it. Our user-defined value type is ready to use. Of course we could override more operators and I guess is-bigger-than and is-lesser-that would be a good idea but it’s easy to do so if you want to extend the struct your good to go. Below you will find complete code for all above and code for unit tests.

Regards, Michał!

Coords
Tests