0% found this document useful (0 votes)
22 views65 pages

Design Pattern Module 1

The document provides an overview of design patterns, defining them as reusable solutions to common design problems in software development. It outlines key elements of design patterns, such as their names, problems, solutions, and consequences, and discusses specific patterns like MVC, Singleton, Factory Method, and others. Additionally, it explains how to select and use design patterns effectively to improve object-oriented design and maintainability.

Uploaded by

Jay Parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views65 pages

Design Pattern Module 1

The document provides an overview of design patterns, defining them as reusable solutions to common design problems in software development. It outlines key elements of design patterns, such as their names, problems, solutions, and consequences, and discusses specific patterns like MVC, Singleton, Factory Method, and others. Additionally, it explains how to select and use design patterns effectively to improve object-oriented design and maintainability.

Uploaded by

Jay Parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Design Pattern

Introduction
What Is a Design Pattern?
• Each pattern describes a problem which occurs over and
over again in our environment, and then describes the
core of the solution to that problem, in such a way that
you can use this solution a million times over, without ever
doing it the same way twice.
• In general, a pattern has four essential elements
• The pattern name is a handle we can use to describe a
design problem, its solutions, and consequences in a word
or two. Naming a pattern immediately increases our
design vocabulary.
• The problem describes when to apply the pattern. It
explains the problem and its context.
• The solution describes the elements that make up the
design, their relationships, responsibilities, and
collaborations.
• The consequences are the results and trade-offs of
applying the pattern. Though consequences are often
unvoiced when we describe design decisions, they are
critical for evaluating design alternatives and for
understanding the costs and benefits of applying the
pattern.
Design Patterns in Smalltalk
MVC
• Looking at the design patterns inside MVC should help
you see what we mean by the term “pattern.”
• MVC consists of three kinds of objects. The Model is the
application object, the View is its screen presentation,
and the Controller defines the way the user interface
reacts to user input.
• Before MVC, user interface designs tended to lump these
objects together. MVC decouples them to increase
flexibility and reuse.
• MVC decouples views and models by establishing a
subscribe/notify protocol between them.
• A view must ensure that its appearance reflects the state
of the model.
• Whenever the model’s data changes, the model notifies
views that depend on it. In response, each view gets an
opportunity to update itself. This approach lets you attach
multiple views to a model to provide different
presentations. You can also create new views for a model
without rewriting it.
• But the design is applicable to a more general problem:
decoupling objects so that changes to one can affect any
number of others without requiring the changed object to
know details of the others.
• Another feature of MVC is that views can be nested.
• MVC also lets you change the way a view responds to user
input without changing its visual presentation.
• You might want to change the way it responds to the
keyboard, for example, or have it use a pop-up menu
instead of command keys.
• MVC encapsulates the response mechanism in a
Controller object. There is a class hierarchy of controllers,
making it easy to create a new controller as a variation on
an existing one.
• A view uses an instance of a Controller subclass to
implement a particular response strategy; to implement a
different strategy, simply replace the instance with a
different kind of controller.
• It’s even possible to change a view’s controller at run-time
to let the view change the way it responds to user input.
• The View-Controller relationship is an example of the
Strategy design pattern.
• A Strategy is an object that represents an algorithm. It’s
useful when you want to replace the algorithm either
statically or dynamically, when you have a lot of variants
of the algorithm, or when the algorithm has complex data
structures that you want to encapsulate.
• MVC uses other design patterns, such as Factory Method
to specify the default controller class for a view and
Decorator to add scrolling to a view. But the main
relationships in MVC are given by the Observer,
Composite, and Strategy design patterns.
• Design patterns are basically defined as reusable solutions
to the common problems that arise during software design
and development.
• They are general templates or best practices that guide
developers in creating well-structured, maintainable, and
efficient code.
• Singleton Pattern
• The Singleton method or Singleton Design pattern is one of the
simplest design patterns. It ensures a class only has one
instance, and provides a global point of access to it.
• Factory Method Pattern
• The Factory Method pattern is used to create objects without
specifying the exact class of object that will be created. This
pattern is useful when you need to decouple the creation of an
object from its implementation.
• Abstract Factory Pattern
• Abstract Factory pattern is almost similar to Factory Pattern and is
considered as another layer of abstraction over factory pattern.
Abstract Factory patterns work around a super-factory which creates
other factories.
• Builder Pattern
• Builder pattern aims to “Separate the construction of a complex object
from its representation so that the same construction process can
create different representations.” It is used to construct a complex
object step by step and the final step will return the object.
• Prototype Pattern Prototype allows us to hide the complexity of
making new instances from the client.
• The concept is to copy an existing object rather than creating a new
instance from scratch, something that may include costly operations. The
existing object acts as a prototype and contains the state of the object.
• Adapter Pattern
• The adapter pattern convert the interface of a class into
another interface clients expect. Adapter lets classes work
together that couldn’t otherwise because of incompatible
interfaces
• Bridge Pattern
• 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.
• Composite Pattern
• Composite pattern is a partitioning design pattern and describes a group of
objects that is treated the same way as a single instance of the same type of
object. The intent of a composite is to “compose” objects into tree structures
to represent part-whole hierarchies.
• Decorator Pattern
• It allows us to dynamically add functionality and behavior to an object
without affecting the behavior of other existing objects within the same class.
• We use inheritance to extend the behavior of the class. This takes place at
compile-time, and all the instances of that class get the extended behavior.
• Facade Pattern
• Facade Method Design Pattern provides a unified interface to a set of
interfaces in a subsystem. Facade defines a high-level interface that makes
the subsystem easier to use.
• Proxy Pattern
• Proxy means ‘in place of’, representing’ or ‘in place of’ or ‘on behalf of’ are
literal meanings of proxy and that directly explains Proxy Design Pattern.
• Proxies are also called surrogates, handles, and wrappers. They are closely
related in structure, but not purpose, to Adapters and Decorators.
• Flyweight Pattern
• This pattern provides ways to decrease object count thus improving
application required objects structure. Flyweight pattern is used when
we need to create a large number of similar objects.
• Observer Pattern
• It defines a one-to-many dependency between objects, so that when one
object (the subject) changes its state, all its dependents (observers) are
notified and updated automatically.
• Strategy Pattern
• that allows the behavior of an object to be selected at runtime. It is one
of the Gang of Four (GoF) design patterns, which are widely used in
object-oriented programming.
• The Strategy pattern is based on the idea of encapsulating a family of
algorithms into separate classes that implement a common interface.
• Command Pattern
• The Command Pattern is a behavioral design pattern that turns a request into
a stand-alone object, containing all the information about the request. This
object can be passed around, stored, and executed at a later time
• Chain of Responsibility Pattern
• Chain of responsibility pattern is used to achieve loose coupling in software
design where a request from the client is passed to a chain of objects to
process them.
• Later, the object in the chain will decide themselves who will be processing
the request and whether the request is required to be sent to the next object
in the chain or not.
• State Pattern
• A state design pattern is used when an Object changes its behavior
based on its internal state. If we have to change the behavior of an object
based on its state, we can have a state variable in the Object and use the
if-else condition block to perform different actions based on the state.
• Template Method Pattern
• Template method design pattern is to define an algorithm as a skeleton of
operations and leave the details to be implemented by the child classes.
The overall structure and sequence of the algorithm are preserved by the
parent class.
• Visitor Pattern
• It is used when we have to perform an operation on a group of similar kind
of Objects. With the help of visitor pattern, we can move the operational
logic from the objects to another class.
• Interpreter Pattern
• Interpreter pattern is used to defines a grammatical representation for a
language and provides an interpreter to deal with this grammar.
• Mediator Pattern
• It enables decoupling of objects by introducing a layer in between so that
the interaction between objects happen via the layer.
• Memento Pattern
• It is used to restore state of an object to a previous state. As your
application is progressing, you may want to save checkpoints in your
application and restore back to those checkpoints later.
• Intent of Memento Design pattern is without violating encapsulation,
capture and externalize an object’s internal state so that the object
can be restored to this state later.
How Design Patterns Solve Design
Problems

 Specifying Object
Implementation
• Finding Appropriate Objects
• Requests are the only way to get an object to execute an operation.
Operations are the only way to change an object’s internal data. Because of
these restrictions, the object’s internal state is said to be encapsulated; it
cannot be accessed directly, and its representation is invisible from outside
the object.
• The hard part about object-oriented design is decomposing a system into
objects. The task is difficult because many factors come into play:
encapsulation, granularity, dependency, flexibility, performance, evolution,
reusability, and on and on. They all influence the decomposition, often in
conflicting ways
• For example, the Composite pattern introduces an
abstraction for treating objects uniformly that doesn’t
have a physical counterpart.
• The Strategy pattern describes how to implement
interchangeable families of algorithms.
• The State pattern represents each state of an entity as
an object
• Determining Object Granularity
• Objects can vary tremendously in size and number. They can
represent everything down to the hardware or all the way up to
entire applications. How do we decide what should be an object?
• Design patterns address this issue as well.
• The Facade pattern describes how to represent complete
subsystems as objects, and the Flyweight pattern describes how to
support huge numbers of objects at the finest granularities.
• Other design patterns describe specific ways of decomposing an
object into smaller objects.
• Abstract Factory and Builder yield objects whose only
responsibilities are creating other objects.
• isitor and Command yield objects whose only
responsibilities are to implement a request on another
object or group of object
• Specifying Object Interfaces
• An object’s interface characterizes the complete set of
requests that can be sent to the object. Any request that
matches a signature in the object’s interface may be sent
to the object.
s
• When a request is sent to an object, the particular
operation that’s performed depends on both the request
and the receiving object. Different objects that support
identical requests may have different implementations of
the operations that fulfill these requests. The run-time
association of a request to an object and one of its
operations is known as dynamic binding.
• Design patterns help you define interfaces by identifying their key
elements and the kinds of data that get sent across an interface. A
design pattern might also tell you what not to put in the interface.
• The Memento pattern is a good example. It describes how to
encapsulate and save the internal state of an object so that the object
can be restored to that state later. The pattern stipulates that
Memento objects must define two interfaces: a restricted one that
lets clients hold and copy mementos, and a privileged one that only
the original object can use to store and retrieve state in the
memento.
• Design patterns also specify relationships between interfaces.
• In particular, they often require some classes to have similar
interfaces, or they place constraints on the interfaces of some
classes.
• For example, both Decorator and Proxy require the interfaces
of Decorator and Proxy objects to be identical to the decorated
and proxied objects.
• In Visitor, the Visitor interface must reflect all classes of objects
that visitors can visit.
• Specifying Object Implementations
• For example, objects in a Chain of Responsibility must
have a common type, but usually they don’t share a
common implementation.
• In the Composite pattern, Component defines a common
interface, but Composite often defines a common
implementation.
• Command , Observer , State , and Strategy are often
implemented with abstract classes that are pure
interfaces.
• The State , Strategy , and Visitor patterns depend on it.
• In the State pattern, an object delegates requests to a State object that
represents its current state.
• In the Strategy pattern, an object delegates a specific request to an
object that represents a strategy for carrying out the request. An object
will only have one state, but it can have many strategies for different
requests. The purpose of both patterns is to change the behavior of an
object by changing the objects to which it delegates requests.
• In Visitor, the operation that gets performed on each element of an
object structure is always delegated to the Visitor object.
Selecting a Design Pattern
• Consider how design patterns solve design problems
• Scan Intent sections
• Study how patterns interrelate
• Study patterns of like purpose.
• Examine a cause of redesign
• Consider what should be variable in your design
• Consider how design patterns solve design problems.
• How Design Patterns Solve Design Problems discusses
how design patterns help you find appropriate objects,
determine object granularity, specify object interfaces,
and several other ways in which design patterns solve
design problems.
• Referring to these discussions can help guide your search
for the right pattern.
• Scan Intent sections.
• Design Pattern Catalog lists the
Intent sections from all the
patterns in the catalog.
• Read through each pattern’s
intent to find one or more that
sound relevant to your problem.
You can use the classification
scheme presented in Table 1.1 to
narrow your search.
• Study how patterns
interrelate.

• Figure 1.1 shows


relationships between
design patterns
graphically. Studying
these relationships can
help direct you to the
right pattern or group
of patterns.
• Study patterns of like purpose.
• The catalog has three chapters,
• one for creational patterns,
• second for structural patterns,
• third for behavioral patterns.
• Each chapter starts off with introductory comments on the
patterns and concludes with a section that compares and
contrasts them. These sections give you insight into the
similarities and differences between patterns of like purpose.
• Examine a cause of
redesign.
• Look at the causes of
redesign to see if your
problem involves one or
more of them. Then look
at the patterns that help
you avoid the causes of
redesign.
• Consider what should be variable in your design.
• This approach is the opposite of focusing on the causes of
redesign.
• Instead of considering what might force a change to a
design, consider what you want to be able to change
without redesign.
• The focus here is on encapsulating the concept that
varies, a theme of many design patterns.
• Table 1.2 lists the design aspect(s) that design patterns let
you vary independently, thereby letting you change them
How to Use a Design Pattern
• Read the pattern once through for an overview.
• Go back and study the Structure, Participants, and Collaborations sections
• Look at the Sample Code section to see a concrete example of the pattern
in code.
• Choose names for pattern participants that are meaningful in the
application context
• Define the classes
• Define application-specific names for operations in the pattern
• Implement the operations to carry out the responsibilities and
collaborations in the pattern

Common questions

Powered by AI

The Factory Method pattern is used to create objects without specifying the exact class of object that will be created, allowing for the creation of objects via interfaces or abstract classes, which enhances flexibility by facilitating object interchangeability . In contrast, the Abstract Factory pattern provides an interface for creating related families of objects without specifying their concrete classes, essentially serving as a super-factory that creates other factories. This pattern offers an additional layer of abstraction over the Factory Method, enabling the creation of complex object structures (families) while still keeping the client code decoupled from concrete classes . Both patterns enhance design flexibility by promoting code reuse and reducing dependency on concrete classes, but the Abstract Factory is particularly useful when dealing with multiple families of related or dependent objects .

In the MVC framework, the Observer pattern plays a role by defining a one-to-many dependency between the model (subject) and the view (observer), allowing the view to update automatically when the model's state changes . The Composite pattern is used to treat both individual elements and compositions of elements uniformly, which can be applied to manage complex view hierarchies within the MVC setup . Together, these patterns enable seamless asynchronous communication between model and view, enhancing the scalability and modularity of the application .

The Visitor pattern separates operations from an object structure by allowing a new operation to be defined without changing the classes of the elements on which it operates. It achieves this by externalizing the process of an operation onto a 'Visitor' class, which means that the operations are decoupled from the objects themselves . The benefits for system maintenance include increased flexibility, as new operations can be added relatively quickly without modifying the existing object structure . Additionally, it allows for the encapsulation of related operations in a single class, making it easier to manage and evolve operations separately from the data structures they act upon .

The Facade pattern addresses system complexity by providing a simplified interface to a set of interfaces within a subsystem, making the subsystem easier to use and understand . It hides the underlying complexity of the subsystems from the client, thus streamlining interactions with the system . On the other hand, the Flyweight pattern improves performance by minimizing memory usage through the sharing of a large number of fine-grained objects, which reduces resource consumption . The relationship between these patterns lies in their complementary roles: the Facade pattern simplifies system use by abstracting complexity, while the Flyweight pattern enhances performance by optimizing object management .

Design patterns address object granularity issues by defining strategies for creating and managing the size and number of objects within a software system. For instance, the Flyweight pattern addresses the issue of supporting a large number of similar objects efficiently by sharing resources among them to minimize memory usage . The Facade pattern simplifies interactions with a complex subsystem by providing a single point of reference, abstracting finer-grained components into a coarser-grained one . These patterns, along with others like Composite for managing tree structures and Builder for constructing complex objects, help developers manage the granularity of objects, ensuring an efficient and scalable system design .

The Decorator pattern solves the problem of dynamically adding responsibilities to an object without modifying its existing code structure. It provides a flexible alternative to subclassing for extending functionality . The pattern involves wrapping the original class with an additional layer that can introduce new behavior . In contrast, the Proxy pattern serves as a surrogate or placeholder for another object to control access to it, often used for purposes such as access control, lazily loading, or control over resource-intensive objects . Therefore, while both patterns add additional behavior, the Decorator focuses on dynamic functionality extension, whereas the Proxy controls access to the original object .

The State pattern allows an object to change its behavior when its internal state changes, effectively making the object appear to change its class . This is achieved by having a separate State object that the main object delegates requests to, depending on its current state. The key distinction from the Strategy pattern is that while the Strategy pattern involves encapsulating interchangeable interfaces, each state is an actual mode of operation for the object . Hence, in the State pattern, the object’s class behavior changes with state changes, whereas, in the Strategy pattern, behaviors can be selected independently without altering the state .

The Composite pattern helps manage the complexity of object hierarchies by allowing individual objects and compositions (groups of objects) to be treated uniformly. This is achieved by defining a common interface for both simple and composite objects, enabling recursive tree structures that represent part-whole hierarchies . The key benefits in software design include increased flexibility and reusability, as you can add new composite objects without altering existing code, and simplified hierarchy management, facilitating tree-like data representations .

The Strategy design pattern enhances flexibility by allowing the behavior of an object to be selected at runtime. It does this by encapsulating a family of algorithms into separate classes that implement a common interface. This means that an algorithm can be changed dynamically at runtime without altering the clients that use it . Key scenarios for applying the Strategy pattern include when you want to replace the algorithm either statically or dynamically, when you have multiple variants of an algorithm, or when you want to encapsulate complex data structures within the algorithm .

The Chain of Responsibility pattern enhances decoupling in software applications by allowing a request to be passed along a chain of handlers, each of which can choose to handle the request or pass it to the next handler. This pattern decouples the sender of the request from its receiver, promoting loose coupling and reducing dependencies between system components . The impact on design flexibility is significant, as it allows for changes in the handling logic without affecting the client code. New handlers can be added easily to the chain, and the processing order can be reorganized by simply re-linking the handlers .

You might also like