Design Ptterns

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

What’s a design pattern?

Design patterns are typical solutions to commonly occurring problems in software


design. They are like pre-made blueprints that you can customize to solve a recurring
design problem in your code.

You can’t just find a pattern and copy it into your program, the way you can with off-the-
shelf functions or libraries. The pattern is not a specific piece of code, but a general
concept for solving a particular problem. You can follow the pattern details and
implement a solution that suits the realities of your own program.

Patterns are often confused with algorithms, because both concepts describe typical
solutions to some known problems. While an algorithm always defines a clear set of
actions that can achieve some goal, a pattern is a more high-level description of a
solution. The code of the same pattern applied to two different programs may be
different.

An analogy to an algorithm is a cooking recipe: both have clear steps to achieve a goal.
On the other hand, a pattern is more like a blueprint: you can see what the result and its
features are, but the exact order of implementation is up to you.

What does the pattern consist of?


 Intent of the pattern briefly describes both the problem and the solution.
 Motivation further explains the problem and the solution the pattern makes
possible.
 Structure of classes shows each part of the pattern and how they are related.
 Code example in one of the popular programming languages makes it easier to
grasp the idea behind the pattern.

Some pattern catalogs list other useful details, such as applicability of the pattern,
implementation steps and relations with other patterns.

Why should I learn patterns?


 Design patterns are a toolkit of tried and tested solutions to common problems
in software design. Even if you never encounter these problems, knowing
patterns is still useful because it teaches you how to solve all sorts of problems
using principles of object-oriented design.

 Design patterns define a common language that you and your teammates can
use to communicate more efficiently. You can say, “Oh, just use a Singleton for
that,” and everyone will understand the idea behind your suggestion. No need to
explain what a singleton is if you know the pattern and its name.

Criticism of patterns
Kludges for a weak programming language 
Usually, the need for patterns arises when people choose a programming language or a
technology that lacks the necessary level of abstraction. In this case, patterns become a
kludge that gives the language much-needed super-abilities.

For example, the Strategy pattern can be implemented with a simple anonymous


(lambda) function in most modern programming languages.

Inefficient solutions
Patterns try to systematize approaches that are already widely used. This unification is
viewed by many as a dogma and they implement patterns “to the point”, without
adapting them to the context of their project.

Unjustified use
If all you have is a hammer, everything looks like a nail.
This is the problem that haunts many novices who have just familiarized themselves
with patterns. Having learned about patterns, they try to apply them everywhere, even in
situations where simpler code would do just fine.

Classification of patterns
Design patterns differ by their complexity, level of detail and scale of applicability to the
entire system being designed. I like the analogy to road construction: you can make an
intersection safer by either installing some traffic lights or building an entire multi-level
interchange with underground passages for pedestrians.

The most basic and low-level patterns are often called idioms. They usually apply only
to a single programming language.

The most universal and high-level patterns are architectural patterns. Developers can
implement these patterns in virtually any language. Unlike other patterns, they can be
used to design the architecture of an entire application.

In addition, all patterns can be categorized by their intent, or purpose. This book covers
three main groups of patterns:

 Creational patterns provide object creation mechanisms that increase flexibility


and reuse of existing code.
 Structural patterns explain how to assemble objects and classes into larger
structures, while keeping the structures flexible and efficient.

 Behavioral patterns take care of effective communication and the assignment of


responsibilities between objects.

In software engineering, a design pattern is a general repeatable solution to a


commonly occurring problem in software design. A design pattern isn't a finished design
that can be transformed directly into code. It is a description or template for how to solve
a problem that can be used in many different situations.

Uses of Design Patterns


Design patterns can speed up the development process by providing tested, proven
development paradigms. Effective software design requires considering issues that may
not become visible until later in the implementation. Reusing design patterns helps to
prevent subtle issues that can cause major problems and improves code readability for
coders and architects familiar with the patterns.

Often, people only understand how to apply certain software design techniques to
certain problems. These techniques are difficult to apply to a broader range of
problems. Design patterns provide general solutions, documented in a format that
doesn't require specifics tied to a particular problem.

In addition, patterns allow developers to communicate using well-known, well


understood names for software interactions. Common design patterns can be improved
over time, making them more robust than ad-hoc designs.

Creational design patterns


These design patterns are all about class instantiation. This pattern can be further
divided into class-creation patterns and object-creational patterns. While class-creation
patterns use inheritance effectively in the instantiation process, object-creation patterns
use delegation effectively to get the job done.

 Abstract Factory
Creates an instance of several families of classes
 Builder
Separates object construction from its representation
 Factory Method
Creates an instance of several derived classes
 Object Pool
Avoid expensive acquisition and release of resources by recycling objects that
are no longer in use
 Prototype
A fully initialized instance to be copied or cloned
 Singleton
A class of which only a single instance can exist
Structural design patterns
These design patterns are all about Class and Object composition. Structural class-
creation patterns use inheritance to compose interfaces. Structural object-patterns
define ways to compose objects to obtain new functionality.

 Adapter
Match interfaces of different classes
 Bridge
Separates an object’s interface from its implementation
 Composite
A tree structure of simple and composite objects
 Decorator
Add responsibilities to objects dynamically
 Facade
A single class that represents an entire subsystem
 Flyweight
A fine-grained instance used for efficient sharing
 Private Class Data
Restricts accessor/mutator access
 Proxy
An object representing another object

Behavioral design patterns


These design patterns are all about Class's objects communication. Behavioral patterns
are those patterns that are most specifically concerned with communication between
objects.

 Chain of responsibility
A way of passing a request between a chain of objects
 Command
Encapsulate a command request as an object
 Interpreter
A way to include language elements in a program
 Iterator
Sequentially access the elements of a collection
 Mediator
Defines simplified communication between classes
 Memento
Capture and restore an object's internal state
 Null Object
Designed to act as a default value of an object
 Observer
A way of notifying change to a number of classes
 State
Alter an object's behavior when its state changes
 Strategy
Encapsulates an algorithm inside a class
 Template method
Defer the exact steps of an algorithm to a subclass
 Visitor
Defines a new operation to a class without change

Criticism
The concept of design patterns has been criticized by some in the field of computer
science.

Targets the wrong problem


The need for patterns results from using computer languages or techniques with
insufficient abstraction ability. Under ideal factoring, a concept should not be copied, but
merely referenced. But if something is referenced instead of copied, then there is no
"pattern" to label and catalog.

Lacks formal foundations


The study of design patterns has been excessively ad hoc, and some have argued that
the concept sorely needs to be put on a more formal footing.

Leads to inefficient solutions


The idea of a design pattern is an attempt to standardize what are already accepted
best practices. In principle this might appear to be beneficial, but in practice it often
results in the unnecessary duplication of code. It is almost always a more efficient
solution to use a well-factored implementation rather than a "just barely good enough"
design pattern.

Does not differ significantly from other abstractions


Some authors allege that design patterns don't differ significantly from other forms of
abstraction, and that the use of new terminology (borrowed from the architecture
community) to describe existing phenomena in the field of programming is unnecessary.

What is Factory Method Design Pattern?


Gang of Four categorizes the factory method design pattern as a creational pattern
since it deals with object creation.  This pattern enforces the loose coupling and
encapsulation principles in object-oriented programming. This pattern applies in
situations where there are sub-classes involved, and the creation of those becomes
complex with the system execution. According to the GoF factory method has following
standard definition,
“An interface for creating an object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses”
In simpler words, object creation is handed over to a separate entity via an interface.
This entity is called the factory, and it contains the object creation code with the help of
an interface or an abstract class to create the suitable object from various class
implementations. Only sub-classes are responsible and decide which class to
instantiate at runtime.
This pattern is also called as a ‘virtual constructor’ because the creation logic is hidden
from the client and only an interface or abstract class will expose the suitable factory
method to the client. Thus, the interface allows separating the object creation code from
the external world.
Here client uses the factory to create object instances.
 

Factory method pattern

Problems solved by Factory Method


 Complex object creation, especially within several layers of class hierarchy
 Usage of new() operator, causing complexity, duplication and inflexibility issues
in application code
 When the client is unauthorized to access in-detail class implementations

When to Use the Factory Design Pattern


 The internal implementation is hidden from the client application or when a class
could not foresee the type of objects it is obliged to create
o There are times when the main application or framework is unaware of the
run-time object creations. Only interfaces or abstract classes are visible to
request the service. In this situation, factory class should come to the
scenery and support the object creation via the abstract method.
 a system needs to be independent of various object creation procedures
 there are different approaches of implementations to one class and the required
implementation needs to be selected at runtime
 parent class decides to delegate the suitable object creation to subclasses
depending on the provided data
 Programming to the interface is strictly enforced in an application, using new()
operator would be a fatal issue which tends to create inflexible and
unmaintainable code.
 An application requires loose coupling, and encapsulation principle build within
the code

 How Factory Method Design Pattern Works


Why do we need to introduce a factory?
Since the application is unaware of internal implementations of each subclass and only
run-time will decide which class implementation to instantiate and use of new() to direct
object instantiation each time will cause performance overhead with inflexibility in the
system.
How the pattern eliminates the problem?
Use a common interface or an abstract class to obtain required methods that are to be
used in factory class
Factory
Contains the separate object creation logic or the factory method to use when
necessary. The client will call this method to get the required object at runtime
How to create the object?
Client delegates the object creation to the factory class specifying the required details at
the run-time and the factory will instantiate the suitable new concrete object instance
using the specific implementation of the sub-class via the factory pattern.

Code Samples
Interface/Abstract Class
Interface which contains the abstract method to use by subclasses.
Concrete Class
Concrete subclasses which implement the interface with full implementation.
Factory / Creator
Create a Factory to generate an object of concrete class based on given information.
Factory pattern encapsulates object creation logic, which makes it easy to change it
later when you change how the object gets created, or you can even introduce a new
object with just change in one class.
Client
The application which requests the object to fulfill the decoration requirement

Advantage of Factory Design Pattern


 Remove the code duplication using the factory class and method
 Subclass implementations are independent of application clients, hence enforce
flexibility, maintainability, and testability
 Eliminate many run-time errors due to service delegation to the factory class
 Maintain the code consistency through consolidating object creation mechanism
within the factory class.
 Encourage the programming to interface principle ensuring the code quality of
the system

Drawbacks or Consequences of Factory


Method Design Pattern
 There might be many different factors to include when selecting the appropriate
subclass to create instances at runtime which results in untidy conditional
statements
 If a class does not include in a parent-child class hierarchy or don’t implement
the interface, it cannot be used within the factory class and not applicable in
factory method pattern
 It’s difficult to hook to already existing classes
 Sometimes makes the code complex and challenging to read since most code
contains the abstractions

You might also like