Design Patterns


Patterns of Design


One of the most important principles that successful designers follow, is that they do not solve all the problems from first principles. That is impossible! It is very important to use time tested solutions to recurring problems. I learnt this the hard way - and that was when I started learning the basics of design patterns.
Each application is unique in itself. You cannot use the same generic solution everywhere. But, each application is a combination of multiple components - that are present in almost everywhere. The real task of a designer is to identify these components. Once you have identified such components of the main application, you can take up the task of solving them using the generic solutions available from the past. This is easier said than done. Identifying these individual components is not such a trivial task. That is what a good designer needs to master.
The time tested Design Patterns give us a chunk of predefined problem components and their solutions. They provide an important direction to the thought process. It is like travelling on a defined path, rather than finding our own way in a forest. It is true that, there are times when we have to deviate from the beaten path, and it is important that we should be able to do it. Hence, it is important that we retain that courage and stamina for when it is required; by following the time tested path when it is available.
These patterns are independent of the semantics of the language we use. Often we spend so much time on the semantics of a language, that we tend to ignore the spirit of design. The design patterns help bridge this gap. They help us use the language in an appropriate way, so that the solution that we get is sturdy and capable of handling more and more changes.
But, one should be careful. Just because we use a design pattern, it is not necessary that we will get an elegant solution to our problem. If not used correctly, it could even add complexity to the design. Hence it is important to understand each of these patterns and their spirit - so that we can identify and apply them where they should be.

Object Oriented Design Patterns

The Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides), brought forth the first set of design patterns, back in 1994. The modularity and perfection of these patterns is obvious from the fact that they have lived over several years, in spite of the huge changes in the world of Software Development. They are useful today, as much as they were. Over time, experts have offered their own patters for more specific problems. We can understand them after we have mastered the 26 basic patterns provided by the Gang of Four.
Before understanding each design pattern, it is important to understand why design patterns are required. One must understand where they are required and where they should not be used.
Coursera

Importance & Need of Design Patterns

Someone made an interesting statement: "The earlier you start coding, the more time you take to complete it!"
It is so true and we have all seen it so many times in real life. Coding without spending enough time on understanding the requirements well, without spending enough time on framing the architecture properly and without an appropriate design for each component of the system is a sure formula for failure. Yet, so many project make all the efforts to follow this path and are naturally led to disaster.
The most important part of any architecture or design is to identify and separate out components that are expected to change differently. Identifying these components requires a lot of experience topped up by understanding the domain. This, coupled with an understanding of the current requirements can lead you to a good architecture followed by a good design.
A good code is possible only when we have a good design. But the converse is not always true. A good code is possible only when the developers understand the spirit of the design as well as that of the language. Choosing the right language to implement and abiding by its spirit, makes the code more efficient, readable and maintainable.

Object Oriented Design

Long long ago, object oriented design was one major step towards achieving a good design and architecture, leading to a good code. Unfortunately, even today, this is one of the most misunderstood topic.
Often, people confuse object oriented languages with object oriented design. Just because you use an object oriented language, it does not mean that any code you write is object oriented. And on the other hand, just because you do not use an object oriented language, it does not mean that your code is not object oriented.
Some consider object oriented design as something superior to traditional structural design. Some think using an object oriented language increases the re-usability of the code. This may not always be true. Using structural design is not a sin! Everything depends upon the problem that you are trying to solve. It depends upon the granularity of the requirements. It depends upon the required trade-off between performance and maintainability.
True object oriented design is a habit. It is a way of thinking. It is a discipline that developers can follow - to make code more readable and maintainable. Some languages make it easier to implement, while others make it easier to violate it. But, in real life, you can see plenty of examples that prove this wrong. There are developers who write miserable code using object oriented languages - and there are some who write perfectly readable and maintainable code with structural languages. It just depends upon the habit and discipline that they follow.
All said, there are a lot of situations where object oriented design is a perfect fit for the type problem you are working. Object oriented design essentially means a design where you conceive various entities in the requirements as an Object - something that has its own behavior and its own state that has an impact on this behavior.
If the requirements fit into the above paradigm, then object oriented design is a great choice. And, using an object oriented language makes the developer̢۪s job easier - since it has several features that make the job simpler.

Using Design Patterns

One of the most important principles that successful designers follow, is that they do not solve all the problems from first principles. That is impossible! It is very important to use time tested solutions to recurring problems. I learnt this the hard way - that is when I started learning the basics of design patterns.
Each application is unique in itself. You cannot use the same generic solution everywhere. But, each application is a combination of multiple components - that are present in almost everywhere. The real task of a designer is to identify these components in the main application and then solving them using the generic solutions available from the past. This is easier said than done. It is really difficult to look at the application with an unbiased mind, to identify its individual components. That is what a good designer needs to master.
These Design Patterns give us a set of predefined problems - along with their solutions. They provide an important direction to the thought process. It is like travelling on a defined path, rather than finding our own way in a forest. It is true that, there are times when we have to deviate from the beaten path, and it is important that we should be able to do it. Hence, it is important that we retain that courage and stamina for when it is required; by following the time tested path when it is available.
These patterns are independent of the semantics of the language we use. Often we spend so much time on the semantics of a language that we tend to ignore the spirit of design. The design patterns help bridge this gap. They help us use the language in an appropriate way, so that the solution that we get is sturdy and capable of handling more and more changes.
But, one should be careful. Just because we use a design pattern, it is not necessary that we will get an elegant solution to our problem. If not used correctly, it could even add complexity to the design. Hence it is important to understand each of these patterns and their spirit - so that we can apply them where they should be applied.
Experts have documented several standards that help speed up our design - by using time tested techniques. The fundamental elements of Object Oriented design are the design patterns. They are specific design solutions for problems that match a given pattern. The design patterns detailed by the famous Gang of Four have been an unchanging part of OOAD. Languages have changed, problems have changed, but the solutions pointed out in these design patterns continue to be relevant and useful.
None of these patterns are better or worse than each other. They are only meant for different situations. Just like none of the notes musical notes in an octave has any meaning in isolation, but when used together in the right way, they can produce beautiful music. Similarly, none of these patterns is used in its pure form. They just provide a direction for thought. A good design will use them in a combination so that they will form an elegant solution. It is for the design to use these patterns in the correct way.
But, at this point, one should be very careful not to forget the basics. One may use a lot of design patterns. One may define several classes and objects. One may have a lot of interfaces and their implementations. But, if the data and functionality is not joined together, the design is not object oriented!

Most Common Design Patterns

The 23 original object oriented design patterns defined by GOF were classified into three groups - Creational Patterns, Structural Patterns and Behavioral Patterns. Over time, people have contributed a lot more to this concept. Now we have more than 50 patterns - which go well beyond the object oriented design. I have tried to include most of them in this list. I have just listed them here. You can find the details in their respective blogs.

Creational Patterns

Creational design patterns are design patterns that deal with object creation mechanisms - defining ways of creating objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by controlling this object creation.

Factory

Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Abstract Factory

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Singleton

Ensure a class has only one instance, and provide a global point of access to it.

Builder

Separate the construction of a complex object from its representation, allowing the same construction process to create various representations.

Prototype

Specify the kinds of objects to create using a prototypical instance, and create new objects from the 'skeleton' of an existing object, thus boosting performance and keeping memory footprints to a minimum.

Dependency Injection

A class accepts the objects it requires from an injector instead of creating the objects directly.

Lazy Initialization

Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. This pattern appears in the GoF catalog as "virtual proxy", an implementation strategy for the Proxy pattern.

Multiton

Ensure a class has only named instances, and provide a global point of access to them.

Object Pool

Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and thread pool patterns.

RAII (Resource Acquisition is Initialization)

Ensure that resources are properly released by tying them to the lifespan of suitable objects.

Structural Patterns

Structural Design Patterns are Design Patterns that help the design by identifying a simple way to realize relationships between entities. The Creational Patterns help us generate objects. But, they leave an open end in associating the objects and identifying the relationships with each other. The structural patterns help us with just that.

Adapter, Wrapper, or Translator

Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator.

Bridge

Decouple an abstraction from its implementation allowing the two to vary independently.

Composite

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Decorator

Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.

Extension Object

Adding functionality to a hierarchy without changing the hierarchy.

Facade

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

Flyweight

Use sharing to support large numbers of similar objects efficiently.

Front Controller

The pattern relates to the design of Web applications. It provides a centralized entry point for handling requests.

Marker

Empty interface to associate metadata with a class.

Module

Group several related elements, such as classes, singletons, methods, globally used, into a single conceptual entity.

Proxy

Provide a surrogate or placeholder for another object to control access to it.

Twin

Twin allows modeling of multiple inheritance in programming languages that do not support this feature.

Behavioral Patterns

Next, we have the Behavioral patterns. The Creational and Structural patterns help us create objects and establish static relationships between them. But, the dynamic behavior - how they interact with each other in a working system is defined by the Behavioral pattern that we use. They identify common communication patterns between objects - this increase the flexibility in communication between objects.

Blackboard

Artificial intelligence pattern for combining disparate sources of data

Chain of responsibility

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Command

Encapsulate a request as an object, thereby allowing for the parameterization of clients with different requests, and the queuing or logging of requests. It also allows for the support of undoable operations.

Interpreter

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

Iterator

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Mediator

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to vary independently.

Memento

Without violating encapsulation, capture and externalize an object's internal state allowing the object to be restored to this state later.

Null object

Avoid null references by providing a default object.

Observer or Publish/subscribe

Define a one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically.

Servant

Define common functionality for a group of classes.

Specification

Recombinable business logic in a Boolean fashion.

State

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Strategy

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Template method

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Visitor

Represent an operation to be performed on the elements of an object structure. Visitor lets a new operation be defined without changing the classes of the elements on which it operates.

Concurrency patterns

Concurrency patterns help you design systems that require heavy multi threading and concurrent access to shared resources.

Active Object

Decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.

Balking

Only execute an action on an object when the object is in a particular state.

Binding properties

Combining multiple observers to force properties in different objects to be synchronized or coordinated in some way.

Blockchain

Decentralized way to store data and agree on ways of processing it in a Merkle tree, optionally using digital signature for any individual contributions.

Compute kernel

The same calculation many times in parallel, differing by integer parameters used with non-branching pointer math into shared arrays, such as GPU-optimized Matrix multiplication or Convolutional neural network.

Event-based asynchronous

Addresses problems with the asynchronous pattern that occur in multithreaded programs.

Guarded suspension

Manages operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed.

Join

Join-pattern provides a way to write concurrent, parallel and distributed programs by message passing. Compared to the use of threads and locks, this is a high-level programming model.

Lock

One thread puts a "lock" on a resource, preventing other threads from accessing or modifying it.

Messaging design pattern (MDP)

Allows the interchange of information (i.e. messages) between components and applications.

Monitor object

An object whose methods are subject to mutual exclusion, thus preventing multiple objects from erroneously trying to use it at the same time.

Reactor

A reactor object provides an asynchronous interface to resources that must be handled synchronously.

Read-write lock

Allows concurrent read access to an object, but requires exclusive access for write operations.

Scheduler

Explicitly control when threads may execute single-threaded code.

Thread pool

A number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. Can be considered a special case of the object pool pattern.

Thread-specific storage

Static or "global" memory local to a thread.

Conclusion

These design patterns are based on wisdom of many experienced developers, who could identify common threads in several systems that they designed. Needless to say, each of these is worth studying. But, it is very important to understand that these patterns are not a fix-all solution. Just following the design patterns does not mean you have a good solution and not following a design pattern does not mean the solution is bad. These patterns only give a direction to your thought. Any sensible design of a worthwhile application will never use the patterns as is. It has to be based on combination and alterations. But in order to do so, it is important to understand the patterns in their pure form.