Design Patterns #3: Decorator

Design pattern number 3 – decorator. The decorator allows to dynamically modify behaviour of an object, and by ‘modify’ I not necessarily mean to swap completely.
The idea behind decorator pattern is that you take an object and wrap it with another object. Calling the outer object (decorator) will in turn call the inner object (component) and before returning any value will do its part with the value.

The example given in the book is a coffee shop where base coffee can be decorated with multiple toppings such as cream, sugar etc. And all those addition will make their own impact on price and name. The important is that the base product (component) and the decorator implements the same interface, the difference is that the decorator has a reference to the component.

And while the decorator itself can be a component it also can be decorated. And so on, and so on… Let’s take a look at the exemplary diagram: the decorator implements the component’s interface and has a reference to a component (we can say in short: the decorator has a component and is a component).

CODE EXAMPLE
Let’s now move on to the code example. My example will be similar to one presented in the book – orders that can be decorated with discounts, extra costs etc. So let’s start with abstractions.

Abstractions
Our IOrder interface will have its name and cost. Decorator interface will extend IOrder with property of IOrder type with public getter only.

Implementations
Concrete classes will be very simple. Order class will have two automatic properties (with private setters) and a constructor that sets those properties.

Things get a bit more complicated with the decorators. Here I will describe only one example but in the source code linked at the bottom of the page you will find two more (however they are very similar). The most important difference (as indicated already twice in this post ;)) is that the decorator has a reference to IOrder object. It will be set int he constructor. As this decorator’s purpose is to apply discount  to the order we will need another property for that (of type int and it will also be set in the constructor). Now the essence of the pattern. As the decorator itself is of type IOrder we need to implement Cost and Name properties. These properties will call counterparting properties in referenced IOrder object, get their values and modify them appropriately. In this case the cost will be reduced by discount value and the name will be equipped with a suffix informing about the discount. We can build as many decorators as we please, and use them as many as we please.

Usage
To test our orders and their decorators we’re gonna instantiate a pack of orders, decorate them and decorate again. They all will be stored in a list and then we will iterate through the list and print to screen their names and cost.

All works perfectly:

That’s it for today. Next week it will be time for factories. So I hope we see again!

Source code: download txt file

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

EratoWPF – Sieve of Eratosthenes (WPF and MVVM)

Hello!
I have just finished another simple app. This time it’s an application to look for prime numbers. The app is again simple but the reason for that is I wanted to make an approach to something new. This time it is MVVM design pattern.
What is MVVM? It is a software design pattern which goal is to separate user interface form application’s logic and data model.
M – model – data source
V – view – user interface
VM – view model – logic and a ‘go-between’ model and view
Use of MVVM pattern allows for a project to be simultaneously developed by a graphic designer and a coder as the UI does not (and should not) require any code-behind. Another advantage is that the whole logic and data-model can be quickly ported to new UI. Microsoft emphasises use of Blend for Visual Studio which is a graphic-design tool for creating (not only, but also) WPF user interfaces to design UIs. In this case I didn’t follow that advice. XAML editor in Visual Studio is sufficient for me.

So, how the separation is achieved? In EratoWPF case, first  I created a model which is PrimeNumbers class in PrimeNumbers.cs file. To be sure that it is working as it should I also created another project called PrimeNumbersSieveTester which is a small console application that tests the class.
Next, I started building the view in XAML with input text boxes and some buttons to run the algorithm or clear inputs.
Finally, I started building the view model. It represents the content of the UI. The view model also privately instantiates the model. The UI will not have access to it.

Binding
To allow the UI use (to display and/or update) properties from view model we use data binding. To achieve that first we need to set data-context for the UI.

The XAML code above will create an object viewModel which is an instance of ViewModel class. The code below will set main grid data-context to viewModel.

Now, to bind a property from viewModel to a control in WPF user interfaces:

The code above binds Text property of a text box to InputRangeStart property in viewModel and IsEnabled to InputsEnabled. Modes specify type of binding. OneWay allows only to dispaly data from viewModelTwoWay allows also to update data in viewModel.
This also requires a view model to implement INotifyPropertChanged. It’s quite simple:

That creates an event handler which is fired every time a property is changed. To set up a property to fire that event it is required to invoke OnPropertyChanged(“PropertyName”); method in a set accessor of this property.

Commands
As it was written earlier in this post, an application designed according to MVVM pattern should not have any code-behind. Therefore, it is required to use commands instead of events.
First, we need to create command class which implements ICommand interface:

That is basic implementation of a command. However, if a command operates on view model instance it is advisable to add private and readonly field for view model and create a constructor that sets it to viewModel defined in XAML.

After that, we need to create an instance of this command in our view model to allow it to be bound to a control in the UI.

Now, to bind the command to a control:

And that’s pretty much it. This is very basic introduction to MVVM, but good enough for a start. There are other aspects of MVVM (such as converters or dependency properties any many many more that I am not aware of at the moment) but I am sure that I’ll come to that as well. As they say: Rome wasn’t build in a day!
Good luck!

Source code: https://github.com/mickaj/EratoWPF
Readme: https://mkajzer.pl/?page_id=200
Installer: https://mkajzer.pl/download/EratoWPF/EratoWPF_installer.zip

Recommended reading (in Polish): “MVVM i XAML w Visual Studio 2015”, Jacek Matulewski, published by Helion, 2016, ISBN: 978-83-283-2867-9
http://helion.pl/ksiazki/mvvm-i-xaml-w-visual-studio-2015-jacek-matulewski,xamlmv.htm

Interfaces

Hello!
Today I’m going to write a word or two about interfaces. So, what are they? In simple words an interface is a statement that a class has certain features defined by the interface. It says that a class is equipped in certain capabilities. Here’s an abstract example. Do you recall pre-smartphones era, circa 2000? Cell phones that time had two primary functions: voice call and text messaging. But some of the fancier models had colour screen, photo camera etc. To reflect that we would say that this fancy phone is of Phone class and implement IPhotoCamera interface.
Let’s create simple Phone class with methods to make a call and send text message:

And a simplest interface I can possibly imagine:

There are few things you need to know about interfaces:
1) Interfaces can consist only of methods, properties, events or indexers
2) Implementation of methods takes place in actual class which inherits the interface. Signature of implementation must be complement with its definition in interface.
3) Interfaces can be generic.
4) Definition of a property interface includes only get; and/or set; accessor keyword without actual implementation.
5) Naming convention is to add capital ‘I’ prefix before the name of an interface.
Let’s get back to our example. Our IPhotoCamera interface contains definition of one property and one method. If a class inherits this interface it must implement what’s defined in the interface.

Now, let’s move back to our main. We can test our two classes by simply invoking methods that are available. But, there’s no use for interfaces so far. This could be easily achieved without it. Class HiEndPhone inherits after CellPhone class and could have its unique method specified without use of interfaces. But using interfaces allows us to write method specifically for objects that implement an interface that will access only what was specified in interface declaration.

But all this above is not the most important thing about interfaces. In C# a class can inherit from only one class. However, this limitation does not include interfaces. You can implement in your class as many interfaces as you want. That’s the most important feature in the concept of interfaces.
To sum things up: an interface is an indication of certain capabilities that a class must implement and actually implement; a class can implement multiple interfaces; naming convention for interfaces is to precede its actual name with capital ‘I’ letter.
Regards, Michal

MSDN: https://msdn.microsoft.com/en-us/library/ms173156.aspx?f=255&MSPPError=-2147217396