Design Patterns – Command and Strategy

These two patterns are quite often mixed up, since they both perform an action when invoked.

However there are quite substantial difference:
1) Command should only be used as a trigger for a more complex action and should have no computational logic.
2) Strategy in the meantime encapsulates logical operations.

In simple terms command should have as little logic as possible, whereas strategy might encapsulate some complex calculations. It is also possible that a command triggers a strategy to be executed.

An example from WPF would be a particular control bound to an instance of ICommand which in turn could run a particular strategy.

Design Pattern – Abstract Factory

Abstract Factories are used to provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Consider an example where we need to create a service for sending data. The data could be sent using various means: by calling a web service, WCF service or by using plain sockets.

To avoid tight coupling the object that sends the data should not be aware of how the data is sent. That’s where abstract factory comes into play. Assuming that all senders implement a  common interface, all the code has to do is call the method that accepts data in whichever format. The benefit of that approach is that we can later easily substitute the protocol for sending data without making any changes to the object that sends data.

In addition, the abstract factory allows the creation of multiple instances of the class responsible for sending data. This is a very useful property when we use dependency injection. The abstract factory can be injected through the constructor and the object responsible for sending data is free to create as many instances of the service as it requires.

That pattern not only solves the coupling problem and separation of concerns, but also allows for better unit testing, since the abstract factory can be very easily mocked.

Blog at WordPress.com.

Up ↑