Design Patterns #5: Command

Fogadtatás,
delayed but here I am with the next design pattern. This time it’s the command pattern. Those who are familiar with the Head First book might be wondering where’s singleton. The Some time ago I wrote a post about singleton (which you can find [here]), so there’s no point in going back. Therefore we go straight to the command.

The command pattern encapsulate calls to objects and provides undo mechanism for those calls. This is achieved by command classes which can perform an action over an object and are assigned to callers. Let’s take a look at the diagram:

Let’s start discussing the above from the ICommand interface and its concrete implementation. The interface has two methods: one for proper action, one for undoing the action. The implementation additionally has reference to IReciever object which defines over what type the command can execute. This is not mandatory, for instance you can declare your execute() and undo() methods to take IReciever as parameter. The important thing is that concrete command operates on certain type, however the caller doesn’t know anything about the receiver, the only responsibility of the caller is (so to speak) to call.

The example in the book is really great. The authors presented a programmable remote controller for an intelligent house. The controller has multiple buttons which can be assigned with a command that can operate lights, home cinema etc.

EXAMPLE
Our example will be programmable counter. The counter will have 5 buttons to manipulate the value of the counter. The counter will have undo feature. This time the code example will have WinForms GUI with custom controls for buttons-callers and counter-receiver.

The caller will have a button to execute a command and a drop-down list to ‘program’ the button with one of the available commands.

 The receiver will have a text-box with current value, button to reset the counter, button to undo last command and a list of all executed commands (operating in FIFO-like mode, the newest on top, the newest first to undo). This user-control will also implement IReceiver interface which provides integer property CounterValue (which play the role of action() method from the diagram) on which the commands will operate and AddToTrace methods which will be used by a command to enroll itself to a command trace for undoing.

Now, the command. Let’s start with the interface:

Beside two already discussed methods Execute() and Undo() the interface provides also Name property (which will be used by the UI) and Receiver property for referencing the counter on which the command will operate.

Concrete command
Now, let’s take a look at one of the commands which implements ICommand interface:

The Execute() method increments the value of the counter and puts the command to the top of the command trace for undoing. The Undo() method simply does the opposite of the Execute() method which is to decrease the counter by one. Removing it from the command trace will be the responsibility of the undo button in the counter user-control.

Command trace
To make it possible we need to keep track of what commands have been executed. For that reason our counter user-control is equipped with a private list that holds objects of type ICommand. The command can enrol itself to the list by invoking AddToTrace method of the receiver and pass itself as an argument.

Once we have the list we can use the undo button which takes the first element off the command trace and invokes the Undo() method.

And that’s it. Take a look how this operates. 

So, that’s it for today. Don’t forget about the source code below and come back next week!

Source code: ZIP file

Design Patterns #4: Factories

Hello there!
It already is a weekend so time for next pattern from the list: factories. Factories are creational-type patterns which means they are used to (surprise, surprise) to create instances. There are three types of factories (of which only latter two are considered as design patterns): simple factory, factory method and abstract factory. Let’s start with the non-pattern one.

SIMPLE FACTORY
Simple factory is a class that has a method to create a certain types of objects where the decision what exactly type to create is made by the factory itself based on given parameters. Assume that we’re building a book store and we want to sell paperbooks, audiobooks and ebooks. We have definitions of a sub-class for each of them implementing IBook base interface. We can build our simple factory in a way that we pass a char parameter and if it matches with first letter of our sub type we create that sub-type:

And that’s it: we have our simple factory. But the problem is that when we want to introduce another sub-type it is necessary to modify that class. And we don’t want that. And why you find [here].

FACTORY METHOD
About factory method I’ve already written [one post]. Consider this post as a supplement to the previous one.
Factory method solves the issue we had with simple factory by removing it’s responsibility to decide (based on the parameter) what type exactly to create. If we want to modify the factory we’ve created above we would need to create separate classes responsible for creating each type of book. And that’s what was done in my [first post] about this pattern:

Now, if we need another sub-type we simply create another class that will create new sub-type.
Let’s take a look at the definition:

Factory method pattern defines an interface enabling to create a single object making the sub-class implementing this interface to decide what exactly type of object to create.

What does the above mean? It means that the client at the point of invocation of factory method doesn’t care (and doesn’t need to care) what type is going to be created: the client wants an object and is going to get one. Very good example is provided by Christopher Okhravi [here] – a simulator a national park where multiple types of animals dwell and the simulator care only about the right number of animals, when it needs an animal to spawn it just calls the factory and the factory decides what animal to create. (I’ve already said that multiple times but I highly recommend his [playlist] about design patterns.)
And now the UML:

We have an abstraction of factory method class and its concretion that creates an instance of a class which is a concretion of one interface common to all sub-types of product.

ABSTRACT FACTORY
If you know how the factory method works understanding the abstract factory will be a piece of cake. Let’s start with the definition:

Abstract Factory provides an interface for creating multiple related or dependent objects without necessity to define their concrete classes.

And the UML:

So, the client uses a factory to create instances. The factory is abstracted by the interface which has multiple (in the case above two) concretions which create two related sub-types of ProductA and ProductB. The IFactory interface doesn’t specify what concrete classes will be instantiated and the client doesn’t care. It is the concretion of the factory which specifies what sub-types of products exactly to create. So, in really really short we may say that the difference between factory method and abstract factory is that the former creates only one type objects while the latter can create multiple types of objects (related and/or dependent).

And that’s it. Before I say goodbye: have a look at the links below to find out more about factories; plan for next week – singleton.

Christopher Okhravi: Factory Method Pattern – Design Patterns (ep 4)
Christopher Okhravi: Abstract Factory Pattern – Design Patterns (ep 5)
CODE Project: Factory Patterns [Snesh Prajapati]

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