Posts

Showing posts with the label Design Patterns

Mediator Pattern

Image
This pattern is best illustrated in code as the source describes it a lot more concisely than in prose. One central class (the mediator) is used by many ‘client’ classes to send messages with (n.b. ‘client’ is my own term not one from the original pattern description). A ‘client’ or several ‘client’ classes then have a reference to this mediator instance as a private field, and use it to send messages. The mediator has an event which each ‘client’ subscribes to. This event is fired each time the mediator sends a message. Example A chat room could use the Mediator pattern, or a system where many ‘clients’ each receive a message each time one of the other clients performs an action (for chat rooms, this would be when each person sends a message). In reality using the Mediator pattern for a chat room would only be practical when used with remoting. Using raw sockets wouldn’t allow for the delegate callbacks (people subscribed to the Mediator class’ MessageReceived event).   ...

Visitor Pattern

The Visitor pattern is a powerful design pattern that I see a lot less than its popular brethren such as Factory, Facade, Command and Singleton. I believe this is because the pattern is often a bit more difficult for developers to understand and much of the articles and examples out there lack a real world example. The Gang of Four defines the Visitor as: Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The very nature of the Visitor makes it an ideal pattern to plug into public API’s, thus allowing its clients to perform operations on a class using a “visiting” class without having to modify the source. Once familiar with this pattern, you will see the opportunity to apply it whenever you are dealing with composites or collections of interfaces/base classes.   A Real World Example I have been working on a project that uses a third-party appl...

Memento Pattern

Image
Delegate some activity to some other class like some helper classes to do the job. The memento pattern is used to encapsulate the current state of an object in a memento object in order to be able to restore the object state later without exposing the internal representation of the object to the outside world. The memento pattern is useful when you have an object which you would to take a "snapshot" of it. So that at a later time we could use the snapshot to restore it to its original state, such as an undo or rollback operation UML Class Diagram Example Suppose we have an object which stores form information and we would like to allow the user to make changes in the form and then if they make a mistake later put back in the original form values. Well, we could serialize the form object and then de-serialize it later but this is obviously messy and not a good solution. Another possible solution would be to have an outside object use the form's methods to pull ...

Iterator Design Pattern

Image
Provide a way to access the elements of aggregate objects sequentially without exposing its representation. We can make the client independent on the movement of the cursors like forward traversal / backward traversal as well as the internal implementation of the list. The actual implementation on how to traverse different types of collections will be different, yet the client code (calling code) should not be concerned about the details of the implementations. The iterator pattern helps to hide such details and provide a generic interface for the client to traverse different types of collections. UML Class Diagram The Iterator interface defines all the methods needed to traverse the collection. The ConcreteIterator class implements the IIterator interface and has the actual implementations on how to traverse the collection. The Aggregate interface defines the methods for the client. The methods that it defines allow the client code not to be bothered with the details on ho...

Observer Design Pattern

Image
The Observer Design Pattern allows us to have a publisher-subscriber framework, whereas change to a publisher will notify all of its subscribers automatically. The subscribers are registered to the publisher so that when a change occurs in the publisher, all of the subscribers are notified.  The publishers and the subscribers are decoupled through the use of interfaces. So that the development of each can vary independently. There are 2 parts in the observer pattern: The first are the subjects. They are the publishers. When a change occurs to a subject it should notify all of its subscribers. The second are the observers. They are the subscribers. They simply listen to the changes in the subjects.  Pattern involved is also called as publish-subscribe pattern. Model view controller (MVC) architecture’s core uses the observer design pattern.   UML Class Diagram Scenario for Observer Pattern Usage  When multiple objects depend on state of one object a...

Command Design Pattern

Image
The command design pattern allows us to store a list of actions those we can execute later. A common example is, storing the undo actions in an application. The undo actions are stored as the user is making changes in an application. When the user decides to perform the undo, the undo actions are retrieved and executed. The benefit of the command pattern is that, it hides the details of the actions that need to be performed, so that the client code does not need to be concerned about the details when it needs to execute the actions. The client code just needs to tell the application to execute the command that was stored. In an undo example, if the user moved a rectangle from position X to position Y, then the undo action will be to move the rectangle from position Y back to position X. The details of this undo action is stored in the command objects so that when the user needs to execute the undo action, the application only need to tell the command object to execute its action w...

Flyweight Design Pattern

Image
The flyweight design pattern allows us to reuse memory spaces in an application when we have lots of objects that are almost identical in nature. For example, if we are writing a game for a smartphone where the amount of memory is very limited and we need to show many angry birds that are identical in shape. We can have only one place that holds the shape of the angry bird instead of keeping each identical shape in the precious memory. In flyweight pattern, there is the concept of Intrinsic and Extrinsic state. Intrinsic states are things that are constant and are stored in the memory. Extrinsic states are things that are not constant and needs to be calculated on the fly, and are therefore not stored in the memory. For example, in the game that we would like to create, the shapes of the Angry Birds are all the same. But their color will change based on how powerful each are. The shapes of the angry birds will be Intrinsic, and the color of the angry bird will be Extrinsic. UM...

Composite Design Pattern

Image
The composite design pattern allows us to set up a tree structure and ask each element in the tree structure to perform a task. A typical tree structure would be a company organization chart, where the CEO is at the top and other employees at the bottom. After the tree structure is established, we can then ask each element, or employee, to perform a common operation. The composite pattern classifies each element in the tree as a composite or a leaf. A composite means that there can be other elements below it, whereas a leaf cannot have any elements below it. Therefore the leaf must be at the very bottom of the tree. The concept is shown in the diagram below, UML Class Diagram Here, we can see the difference between a composite element and the leaf. The IComponent interface defines the methods that both the Composite class and the Leaf class must implement. The Operation method is the common method that all elements in the tree structure can perform. The IComponent simply r...

Bridge Design Pattern

Image
The bridge design pattern allows us, to separate the abstraction from the implementation. In the bridge pattern there are two parts, the first part is the Abstraction, and the second part is the Implementation. The bridge pattern allows the Abstraction and the Implementation to be developed independently, and the client code can access only the Abstraction part without being concerned about the Implementation part.   UML Class Diagram Elements of Bridge Design Pattern Abstraction – core of the bridge design pattern and defines the crux. Contains a reference to the implementer. Refined Abstraction – Extends the abstraction takes the finer detail one level below. Hides the finer elements from implementer. Implementer - This interface is the higher level than abstraction. Just defines the basic operations. Concrete Implementation – Implements the above Implementer interface by providing concrete implementation. Real time scenario For example, inside a house there...

Facade Design Pattern

Image
The facade design pattern allows us, to provide a simplified interface from multiple class libraries. It provides a simple interface that hides the complexity of the class libraries being used. UML Class diagram For example, if the client code needs to access three different class libraries for a single functionality, instead of having the client code accessing those 3 class libraries, we can just create another class, that calls the required class libraries and have the client access only the class that you have created. The result is a simplified interface for the client and the client will not need to know the details of the actual (three) class libraries. Real World Examples for Facade Pattern A MortgageApplication object, which provides a simplified interface to a large subsystem of classes measuring the credit worthiness of an applicant. Implementation of above example in C#.Net Create Customer class, public class Customer { private string _name; ...

Decorator Design Pattern

Image
The decorator design pattern allows you to add features to an object dynamically. Inheritance is used to extend the abilities of ‘a class’. Unlike inheritance, we can choose any single object of a class and modify its behavior leaving the other instances unmodified. While implementing the decorator pattern, we construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance. UML Class Diagram Implementation of decorator pattern Let's look an example to see how it works. ice-cream is an classic example for decorator design pattern. In our example, we have a plain ice cream where we can add different combination of toppings to it. using System; namespace DesignPatterns.Decorator { public interface IIceCream { void MakeIceCream(); } } The above is an interface depicting an ice-cream. Following class is a concrete implementation of this interface. This is the b...

Proxy Design Pattern

Image
The proxy design pattern allows you to provide an interface to other objects by creating a wrapper class as the proxy. The wrapper class, which is the proxy, can add additional functionality to the object of interest without changing the object's code. Below are some of the common examples in which the proxy pattern is used, Adding security access to an existing object. The proxy will determine if the client can access the object of interest.  Simplifying the API of complex objects. The proxy can provide a simple API so that the client code does not have to deal with the complexity of the object of interest. Providing interface for remote resources, such as web service or REST resources.  Coordinating expensive operations on remote resources by asking the remote resources to start the operation as soon as possible before accessing the resources.  Adding a thread-safe feature to an existing class without changing the existing class's code. In short, the proxy ...

Adapter Design Pattern

Image
What is Adapter Pattern? An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need.                  In real world the easy and simple example that comes to mind for an adapter is the travel power adapter. American socket and plug are different from India. Those interfaces are not compatible with one another. India plugs are cylindrical and American plugs are rectangular. We can use an adapter in between to fit an American (rectangular) plug in India (cylindrical) socket assuming voltage requirements are met with. How to implement adapter design pattern? Adapter design pattern can be implemented in two ways. One using the inheritance method and second using the composit...

Prototype Design Pattern

Image
Prototype design pattern is a pattern where new instances of a class are created by cloning an initial object. Reasons for using this design pattern are, - Creating an object is time consuming and a costly affair and you already have a most similar object instance in hand. - Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs. UML Class Diagram When we are not in a situation, in which we can call an object constructor directly, we will clone a pre-existing instance of the object (our prototype). Rather than creating more and more instances of said object, it is possible to save overhead by cloning an existing copy of your object. When working with this design pattern, we must create a class using the abstract modifier.i.e., It will be the only class our object will implement/inherit from. One thing to consider when using this design pattern is, determining wheth...

Builder Design Pattern

Image
Builder focuses on constructing a complex object step by step and final step will returns the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object. "Separate the construction of a complex object from its representation so that the same construction process can create different representations." Example: We can consider construction of a home. Home is the final end product (object) that is to be returned as the output of the construction process. It will have many steps, like basement construction, wall construction, roof construction and so on. Finally the whole home object is returned. Here using the same process you can build houses with different properties. What is the difference between abstract factory and builder pattern?   Abstract factory may also be used to construct a complex object. Then, what is the difference with builder pattern? Builder pattern emphasis is...

Abstract Factory Pattern

Image
Provide an interface for creating families of related or dependent objects without specifying their concrete classes Provides a way to encapsulate a group of individual factories those have common theme. Abstract Factory emphasizes a family of product objects (either simple or complex). Client does not know/care which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. It separates details of implementation of a set of objects from their general usage. Example , consider a program that assists with the packaging and delivery of items for a web-based store. The company delivers two types of product. The first is a standard product that is placed in a box and delivered through the post with a simple label. The second is a delicate item that requires shockproof packaging and is delivered via a courier that requires a detailed manifest. In this case, there are two types of object required, a packaging obje...

Factory Design Pattern

Image
What is it? The Factory Design Pattern is of type Creational Pattern . The official definition for the Factory pattern is:  Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. This pattern is used to replace a class constructor(s), allowing the type of object to be instantiated to be determined at run-time as opposed to design-time, and is used to control a class instantiation. The use of this design pattern reduces the coupling between classes, and offers much more flexibility in the future if the requirements of your application changes, which often happens. One tangible benefit of the Factory pattern is it allows the client to focus on its role in the architecture because it allows for separation of the creation & instantiation of objects from the client. Implementation: To implement the Factory design pattern we will create an Interface which will define t...