A design pattern is a way of reusing abstract knowledge about a problem and its solution. Design patterns are a common way of solving well-known problems that crop up in all kinds of applications. A pattern is a description of the problem and the essence of its solution. It should be sufficiently abstract to be reused in different settings. Pattern descriptions usually make use of object-oriented characteristics such as inheritance and polymorphism. All design patterns are language neutral.
Design patterns were first described in the book 'Design Patterns – Elements of Reusable Object-Oriented Software' written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, also known as the Gang of Four. The book catalogues 23 design patterns as shown below and since then, many more design patterns have been invented.
Creational Pattern
Abstract Factory
Builder
Factory Method
Prototype
Singleton
Structural Patterns
Adapter
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Behavioural Patterns
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template
Visitor
The advantages of using design patterns are:
Not reinventing the wheel
◦ By leveraging the hard work of other developers who had gone through a similar exercise and found good solutions that you can use.
Building resilient code
◦ Design patterns protect the software from changes and additions.
Design patterns are not algorithms and they are not code. It is an approach to thinking about software design that incorporates the experience of developers who had similar problems and fundamental design principles that guide how to structure software designs.
Design Pattern strategies
Sometimes there are different ways (or strategies) to do a task.
Design using Inheritance
Our initial design is to have a superclass Duck and several duck subclasses to model the mallard duck, red head duck, etc. as shown in Figure. These duck subclasses would inherit the methods in the superclass: display(), quack() and swim() because all ducks can quack and swim.
Design using inheritance
Design using Interfaces
Suppose we take out the variations in the duck context class and put these into separate classes. With interfaces, we can have some (but not all) of the duck types behaviours as shown in Figure. So ducks that can fly like the mallard duck and red head duck will inherit the Quackable interface.
Ducks that don’t fly and don’t quack don’t have to inherit any interfaces as shown in below Figure.
Design using interfaces