Lecture-Design Pattern
Lecture-Design Pattern
Lecture 1:
Basic object-oriented
development and design
pattern concepts
Basic object-oriented development(OOD)
Develop
4 Draw state chart diagrams: Systems
class
The class diagrams are used to draw state chart diagrams, design
which help in understanding complex processes that diagrams
cannot be fully derived by the sequence diagrams.
5 Systems design: Draw state
Systems design means modifying the existing system and chart
that implies modifying the diagrams drawn in the previous diagrams
phase. These diagrams can be used to derive classes, their
attributes, and methods. The analyst will need to write
class specifications for each class including the attributes,
methods, and their descriptions.
6 Develop and document the system:
UML is, of course, a modeling language. An analyst may
create wonderful models, but if the system isn’t developed
there is not much point in building models.
Example : Vehicle Rental System
A Car Rental System is an online booking system tailored to the demands of car rental firms, travel agencies,
and companies. It provides a full-featured booking system which allows consumers to check vehicle availability
and make online reservations directly from the website.
Step 1 : Define the use case diagram
Use cases represent high-level functionalities and how a user will
handle the system.
An actor is an entity that initiates the use case from outside the scope of
a use case. It can be any element that can trigger an interaction with the
use case. One actor can be associated with multiple use cases in the system.
Following rules must be followed while drawing use-case for any system:
Activity diagram is basically a flowchart to represent the flow from one activity to another
activity. The activity can be described as an operation of the system. Activity is a particular
operation of the system. Activity diagrams are not only used for visualizing the dynamic nature
of a system, but they are also used to construct the executable system.
• Faster Development: OOD has long been touted as leading to faster development. Many of
the claims of potentially reduced development time are correct in principle, if a bit overstated.
• Reuse of Previous work: This is the benefit cited most commonly in literature, particularly in
business periodicals. OOD produces software modules that can be plugged into one another,
which allows creation of new programs. However, such reuse does not come easily. It takes
planning and investment.
• Increased Quality: Increases in quality are largely a by-product of this program reuse. If 90% of
a new application consists of proven, existing components, then only the remaining 10% of the
code has to be tested from scratch. That observation implies an order-of-magnitude reduction
in defects.
• Modular Architecture: Object-oriented systems have a natural structure for modular design:
objects, subsystems, framework, and so on. Thus, OOD systems are easier to modify. OOD
systems can be altered in fundamental ways without ever breaking up since changes are
neatly encapsulated. However, nothing in OOD guarantees or requires that the code
produced will be modular. The same level of care in design and implementation is required to
produce a modular structure in OOD, as it is for any form of software development.
• Client/Server Applications: By their very nature, client/server applications involve transmission
of messages back and forth over a network, and the object-message paradigm of OOD
meshes well with the physical and conceptual architecture of client/server applications.
• Better Mapping to the Problem Domain: This is a clear winner for OOD, particularly when the
project maps to the real world. Whether objects represent customers, machinery, banks,
sensors or pieces of paper, they can provide a clean, self-contained implication which fits
naturally into human thought processes.
Lecture 2:
Elements of design pattern,
Description of a design
pattern
What Is A Design Pattern?
In software engineering, design pattern is a description or template for how to solve a problem
that can be used in many different situations .A design pattern isn't a finished design that can be
transformed directly into code. Repeatable solutions of commonly occurring problem in software
design.
• 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.
• Patterns provide common design vocabulary, improve communication, ease implementation &
documentation
Why is it used ?
▪ 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.
▪ With carefully tested and proven development paradigms, design patterns can help speed
up your software development process. Instead of tearing your hair out trying to come up
with a suitable design by yourself, just find a design pattern that matches your
requirements and apply it.
▪ 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.
▪ Design patterns provide general solutions, documented in a format that doesn't require
specifics tied to a particular problem.
▪ Design patterns allow ease of communication between software developers.
History and evolution of design Patterns
• Structural patterns generally deal with relationships between entities, making it easier
for these entities to work together. If you want to form larger structures from different
classes and objects as well as provide new functionalities to them, structures design
patterns are all that you need.
• Behavioral patterns are used in communications between entities and make it easier
and more flexible for these entities to communicate. Behavioral design patterns really
come into play if you want to deal with communication between objects.
Creational Patterns
Application-Level Smells
Mysterious Naming Perhaps the most common refactoring's Change Function
Declaration (124) (to rename a function), Rename Variable (137),
and Rename Field,(244). People are often afraid to rename things,
thinking it’s not worth the trouble, but
a good name can save hours in the future
Duplicate Code Similar code in more than one location, Duplication means that
every time you read these copies, you need to read them carefully
to see if there’s any difference.
Shotgun Surgery Avoid Making any modifications requires that you make many
small changes to many different classes.
Code smells
Class Level Smells
Large Class Class trying to do too much and has too many instance variables
Feature Envy Class with a method that seems more interested in other class than the one
it is in
Divergent Code A class that suffers many kinds of changes to bring a change in a system
Inappropriate Intimacy A class that has dependencies on implementation details of other class
Parallel Inheritance Every time you make a subclass for a single class, you are needed to make
Hierarchy subclass for others
Message Chains Method calling a different method which calls a different method which
calls a different method… and on and on
Too Many Parameters A very long list of parameters
Oddball Solutions When multiple methods are used to solve the same problem in one
program creating inconsistency
God Line An excessively long line of code
Excessive Returner A method that returns more data than what its caller needs
Identifying and removing code smells, as seen above, is a tiresome and indefinite
process with no particular result if the software would be smell free or not. Also, as it’s near
impossible to find and remove all smells manually, using automated code review tools that
can identify smells becomes a necessity. Many code review tools help in such operations,
but most of them are either dedicated to one programming language or are not decisive
enough. CodeGrip is one such tool that is focused on improving code quality, having a
feature to identify and display code smells within minutes.
CodeGrip analyses your repositories from Github, BitBucket, and other platforms and
displays the number of code Smells under the maintainability tab also displaying technical
debt to remove these smells. CodeGrip’s state of the art, suggestive engine helps you
classify and resolve code smells easy and individually one at a time. It also organizes each
code smell based on severity and time to resolve, so that developers can schedule and
solve these issues easily while suggesting a solution as well. CodeGrip makes removing
code smells easier than ever, increasing efficiency and decreasing workload.
Eliminating code smells with refactoring
Code refactoring is one of the most effective ways to eliminate code smells and maintain good
code. Refactoring is a restructuring process that attempts to make code cleaner, more concise and
more efficient without altering its core functionality. Refactoring helps ensure that code meets a
team's guidelines (Architecture/design guideline, Coding concentration etc. ) and aligns with a
defined architecture.
Refactoring is a process of improving your codebase without creating new functionality. It helps
you clean up your code and simplify design.
”Refactoring is the process of changing a software system in such a way that it does not alter the external
behavior of the code yet improves its internal structure. It is a disciplined way to clean up code that
minimizes the chances of introducing bugs. In essence when you refactor you are improving the design of
the code after it has been written.” - Martin Fowler
When to do it ?
It is good practice to clean up existing code before programmers add any new code. Another good
time to refactor code is after a team has deployed code into production.Then developers would
have more time to clean up code before they're assigned a new task or a project. Make sure there
is complete test coverage before refactoring an application's code. Otherwise, refactoring process
may work on incomplete application code for no gain.
Lecture 4
Designing for change, Code
smells and Refactoring
When to Refactoring?
When adding features:
The best time for refactoring is before adding new features or updates to existing code.
Doing so can help improve the product's quality. By cleaning the code base before adding
new features or updates, it helps to make the product more robust and easier to use in the
future.
Rule of Three:
✓ 1. When you doing something for the first time just get it done.
✓ 2. The second time around, you may be a bit faster, but the code still won't be as clean
as it should be.
✓ 3. When you do something for the third time, start refactoring.
▪ Duplicates - identical functions or variables. And there can also be identical methods in
objects but described in each of them separately.
▪ Incorrectly formatted code fragments - functions and loops not written correctly, extra
spaces from the beginning of a line, etc.
Refactoring Techniques
Refactoring encompasses a number of specific code hygiene practices.
When it comes to eliminating code smells, however, there are three
particularly effective techniques:
▪ Composing methods : Focuses on methods,
▪ Simplifying method calls : Focuses on the method calls and
▪ Refactoring by abstraction: Focuses on classes.
Composing methods :
Writing a long methods that are very hard to change. This technique is
mainly used in cases where the code is extremely hard to understand.
1. Extraction breaks down the code into smaller chunks to find and Extraction
extract fragments. It then moves the fragments to a new method
and calls it. The fragments are then moved to a new method and
replaced with new content.
Refactoring by abstraction
Finally, refactoring by abstraction comes into play when large chunks of code contain duplications
or redundancies. There are two techniques that constitute this approach, both of which focus on
class inheritance:
1. Pull up: It pulls code parts into a superclass and helps in the elimination of code duplication.
2. Push down. Method code that lives within a superclass but is only used by a few of the
subclasses is pushed down to those respective subclasses.
Refactoring Technique: Refactoring by Abstraction
The IsLogMessageValid method
returns true if the log message is not
considered valid if it contains a null or
empty string.
• The log message is considered invalid
if it contains any sensitive data, such
as a Social Security or credit card
number.Unfortunately, this approach
is a little redundant.
• Programmers would need to write
the same logic twice -- one for each
of the two classes -- to check if the
log messages are valid. A better way
is to refactor these two classes and
create an abstract class.
In the code segment below, notice how
the IsLogMessageValid method has
moved to an abstract class, which helps
mitigate potential code redundancy.
WHY SHOULD WE REFACTOR?
▪ Functions and variables with unclear names
▪ An excessive amount of text in one method
▪ A superfluous amount of comments
▪ Incorrectly formatted code fragments - functions and loops not written correctly,
extra spaces from the beginning of a line, etc.
▪ Refactoring Improves the Design of Software:
Without refactoring, the internal design—the architecture—of software tends to decay.
As people change code to achieve short-term goals, often without a full understanding
of the architecture, the code loses its structure. It’s quite imposable to review the design
looking on the code also harder to prevent. Loss of the structure of code has a
cumulative effect. Regular refactoring helps keep the code in shape and an important
aspect of improving design is to eliminate duplicated code. It’s not that reducing the
amount of code will make the system run any faster. Make a big difference in
modification of the code. The more code there is, the harder it is to modify correctly and
time consuming.
WHY SHOULD WE REFACTOR?
▪ Refactoring helps to find Bugs :
After Refactoring one can get clear understanding what the code does, and easy to put
that new understanding right back into the code. By clarifying the structure of the
program, one can clarify certain assumptions Also he can’t avoid spotting the bugs.
Refactoring helps much more effective at writing robust code.
▪ Refactoring Helps for Program Faster:
Refactoring helps to develop code more quickly. Because of sounds counterintuitive
code. It improves quality. Better internal design, readability, reducing bugs—all these
improve quality. Every new feature requires more and more time to understand how to
fit it into the existing code base, and once it’s added. Software with a good internal
design allows me to easily find how and where I need to make changes to add a new
feature.
▪ Refactoring Makes Software Easier to Understand:
When change come developer need to understand the code written by different people.
Refactoring helps me make the code more readable. Before refactoring, code that works
but is not ideally structured. A little time spent on refactoring can make the code better
communicable and clearly to understand .
Case Study : Code Smells
Fixing and Avoiding the Message Chain Code Smell
Message chain consist of a chain of method calling which creates code smells.
Write down few lines of source code as an example (in any preferred OO
programming language) as an example and explain and analyze, why to avoid ?
Lecture 5
Designing for change, Code
smells and Refactoring
Refactoring legacy code
The goal of refactoring legacy code is to make it easier to understand and work with. It
aims to improve the structure of the code by reducing redundant or erroneous entries.
One of the main advantages of refactoring in legacy code is that it can be done on any
software architecture. It allows developers to focus on improving the quality of the code
without the need for unnecessary downtime.
Project is dealing with legacy PHP core functionalities; it is important to identify how well-
documented and operationally robust the software is.
Refactoring legacy code
There are plenty of tooling options available to automate the code refactoring process,
including SonarQube, Visual Studio IntelliCode, Rider and Eclipse IDE. Many of these tools
enable programmers to execute code restructuring alongside the actual development
process, which can help teams speed up release cadences when needed.
▪ It's a discipline that helps keep the code running smoothly and without introducing
bugs. Another benefit of refactoring is that it allows the developers to focus on the
details that will drive the implementation of the solution instead of just the code itself.
▪ With the proper refactoring techniques, you can get rid of outdated software
applications and improve their overall functionality without compromising their current
state.
Case Study : Code Refactoring
Fixing and Avoiding the Message Chain Code
View the below example :
person.GetBirthDate(20128, 5).GenerateReport().ConvertToSpreadsheet().Print();
Gang of Four ( Gamma, Helm, Jonson, and Vlissides are commonly known GOF) noticed
some design problems and solutions are always very common in a specific context.Key
objectives are using design pattern are :
Need of Design pattern
▪ Enables efficient communication between designers.
▪ Solves an issue just by referring to pattern name.
▪ Improves code readability for coders.
▪ Reduce the time to find the solution by reusing tested and proven development
paradigms.
▪ Reduce the time for coders.
▪ Introduces additional levels of indirection to achieve flexibility.
▪ Reduce the time for understanding the design.
▪ Avoid those alternatives which avoid reusability thereby reducing variations.
▪ Improves design understandability and documentation.
▪ Helps to understand the basics of object-oriented design more easily and quickly.
Essential Element of Design Pattern:
There are four essential elements of a design pattern. They are as follows:
• Pattern Name: It is a unique name that describes a design problem. Pattern name being concise
and meaningful, Improves communication, among developers and helps to design patterns at
higher levels of abstraction.
• Problem: It states the problem and its context such as how to represent the algorithm as
objects (It ensure when the pattern is applicable and what condition should be met before the
pattern is used.
• Solution: It provides a Description of elements that make the design pattern such as their
responsibility, relationship, and collaboration). Pattern solutions cant describe a particular
implementation because patterns are like templates that are applicable to several similar
situations. The solution gives a generic arrangement of classes and objects to solve a problem.
• Consequences: As the name implies these highlight the result, pros and cons of applying the
patterns, etc,(It Describes the impacts on the system’s portability, extensibility. They determine
the costs and evaluate design alternatives of pattern, language, and implementation issues.
Organization of design patterns
Adaptor: Id Adapt or converts an interface of a class into another one according to the client
expectation and hence, overcomes the problem of incompatible interfaces thereby enabling the
classes to work together.
Builder: It Separates the complex objects constructions from their representation in order to create
different representations with the same construction process.
The Catalog of Design Patterns:
Chain Of Responsibility: It Enables the handling of command objects by passing them to other
objects by using the logic present in the processing of objects. In other words, Its decouples sender
and receiver by formatting a chain of receiving objects to pass the request until the request is
handled by an object.
Command: It encapsulates the action and its parameters and hence, enables to parameterize the
different requests of the clients such as long or queue requests. It also assists undoable operations.
Composite: It represents the objects in a tree structure where each object represents the same
interface. This enables clients to treat individual objects and their compositions uniformly.
Decorator: It Adds additional functionality to a class at runtime. This Enables flexibility to subclass
for adding functionality.
Flyweight: It Performs sharing of common objects properties by a large number of objects to save
space.
Interpreter: It Deals with the implementation of a specified computer language that solves specific
problems. It interprets sentences in language by representing the grammar of language along with
an interpreter.
Mediator: It provides a unified interface to the set of interfaces in a subsystem. It provides loose
coupling which enables objects to refer to each explicitly and also varies objects interaction
independently.
The Catalog of Design Patterns:
Momento: It supports the rollback mechanism by enabling the objects, to restore to their previous
state without violation of encapsulation.
Observer: Whenever an object changes its state, it raises an event that notifies other objects and
updates them automatically. This defines a one-to-many dependency between the objects.
Prototype: Here Prototypical instance determines the type of objects to be created. Further new
objects are created by cloning this prototype.
proxy: It provides an illusion by applying placeholder to other objects in order to have control over it.
Singleton: It Provides restrictions on instantiating a class to a single object and also makes it globally
accessible.
State: It Permits an alteration in the object’s behavior with alteration in its state .i.e allows objects
type to change at runtime.
The Catalog of Design Patterns:
Visitors: It Describes the skeleton of a program, enables subclasses to define some steps of the
algorithm, and also to redefine certain steps without affecting the structure of the algorithm.
Strategy: It defines the Family of algorithms and their selection based upon the clients.
Lecture 8
Detailed pattern study:
Singleton, Abstract Factory
Singleton
▪ “Objects may access them globally, which means
an object can have a global scope.”
▪ Unit testing is more difficult (because it introduces a global state into an application).
▪ This pattern reduces the potential for parallelism within a program, because to access the singleton in
a multi-threaded system, an object must be serialized (by locking).
Step 1 :
Let's think about a class which has private constructor. It becomes a class that can't be instantiated
because it has private constructor.
class SingletonObject {
private:
getInstance(){}
};
Step 2 :
We need to have an instance of the class to call it, but we can't have an instance because no other
class can't instantiate it. We can use the constructor from an object of type MyClass but we can never
instantiate that object because no other object can use:
new MyClass();
Implementation
Step 3:
using a static method
Singleton
Abstract Factory patterns work around a super-factory which creates other factories. This factory
is also called as factory of factories. This type of design pattern comes under creational pattern
as this pattern provides one of the best ways to create an object.
In Abstract Factory pattern an interface is responsible for creating a factory of related objects
without explicitly specifying their classes. Each generated factory can give the objects as per the
Factory pattern.
Abstract Factory Implementation
We are going to create a Shape interface and a concrete class implementing it. We create an abstract factory class
AbstractFactory as next step. Factory class ShapeFactory is defined, which extends AbstractFactory. A factory
creator/generator class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass
information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs.
Implementation
1 2
3 4
Lecture 9
Detailed pattern study:
Builder
Builder Design Pattern:
The Builder Design Pattern builds a complex object using many simple objects and using a step-
by-step approach. The Process of constructing a complex object should be generic so that the
same construction process can be used to create different representations of the same complex
object.
So, the Builder Design Pattern is all about separating the construction process from its
representation. When the construction process of your object is very complex then only you
need to use to Builder Design Pattern. If this is not clear at the moment then don’t worry we will
try to understand this with an example.
Please have a look at the following diagram. Here, Laptop is a complex object. In order to build a
laptop, we have to use many small objects like LCD Display, USB Ports, Wireless, Hard Drive,
Pointing Device, Battery, Memory, DVD/CD Reader, Keyboard, Plastic Case, etc. So, we have to
assemble these small objects to build laptop complex objects.
Builder of Design Pattern:
Let us understand the builder design pattern with one real-time example. Suppose we want to
develop an application for displaying the reports. The reports we need to display either in Excel or in
PDF format. That means, we have two types of representation of my reports. In order to understand
this better, please have a look at the following diagram.
Builder of Design Pattern:
As you can see, in the above image, we are generating the report either in Excel and PDF. Here, the
construction process involves several steps such as Create a new report, setting report type, header,
content, and footer. If you look at the final output we have one PDF representation and one Excel
representation. Please have a look at the following diagram to understand the construction process
and its representation.
Builder of Design Pattern:
Let us understand the class diagram and the different components involved in the Builder Design
Pattern. In order to understand this please have a look at the following diagram.
Builder of Design Pattern:
To separate the construction process from its representation, the builder design pattern Involve four
components. They are as follows.
Builder: The Builder is an interface that defines all the steps which are used to make the concrete
product.
Concrete Builder: The ConcreteBuilder class implements the Builder interface and provides
implementation to all the abstract methods. The Concrete Builder is responsible for constructs and
assembles the individual parts of the product by implementing the Builder interface. It also defines
and tracks the representation it creates.
Director: The Director takes those individual processes from the Builder and defines the sequence to
build the product.
Product: The Product is a class and we want to create this product object using the builder design
pattern. This class defines different parts that will make the product.
Lecture 10
Detailed pattern study:
Adapter
Adapter design pattern
The Adapter design pattern is a structural pattern that allows incompatible interfaces to work together.
Adapters are used when incompatible interfaces are involved.
In a situation , object wants to call a method but it is not able to because the interface which our client
object can use, is not available with the code which our client object wants to call. Based on what an
adapter does the adapter design pattern is also called wrapper pattern, translator pattern. Let’s look at
the various participants (objects, interfaces) involved in an adapter pattern.
GoF Definition, “Prototype Design Pattern specifies the kind of objects to create
using a prototypical instance, and create new objects by copying this
prototype”.
Prototype pattern as being based on prototypal inheritance in which we create objects that act as
prototypes for other objects. The prototype object itself is effectively used as a blueprint for each
object the constructor creates. If the prototype of the constructor function used contains a property
called name for example (as per the code sample that follows), then each object created by that
same constructor will also have this same property
Explore How Prototype Pattern Works ?
Try to copy one object to another object using the assignment (=) operator, then both the objects will
share the same memory address. And the reason is the assignment operator (=) copies the reference, not
the object except when there is a value type field. This operator will always copy the reference, not the
actual object. Please have a look at the following image.
As you can see in the above image, we have one Employee class. Then we create an instance of Employee
class (i.e. emp1) and set its Name and Department properties. Then we create another employee instance
(i.e. emp2) by assigning the existing employee object (i.e. emp1). When we change the Name of emp2
then it also changes the name of the emp1.
Explore How Prototype Pattern Works ?
Developers use Prototype design pattern when the Object creation is an expensive undertaking and requires a
ton of time and assets and you have a comparative item previously existing. Prototype pattern gives a
component to duplicate the first item to another object and afterwards adjust it as per the requirements.
When we talk about object cloning it means it is all about the call by value. So, if we do any changes to one
object then it will not affect the other object. Let us see how to clone the object to another object.
Step 1:
Employee class, we created one method i.e.
GetClone and as part of that method, we are
returning a clone object using
theMemberwiseClone method.
Step 2:
First we are creating a new instance of the
Employee class and assigning the properties with
some values.
Step 3:
Next, creating the second object by calling the
GetClone method which in turn returns a new
complete copy of the emp1 object.
1
2
Application of Prototype Design Pattern:
There are many practical scenarios where this design pattern really helps. Here follows few of them.
• Session replication from one server to another server:
In an enterprise level application managing a server pool, the application will monitor and
maintain the optimum load on individual server in the pool. In case of the catastrophic failure,
one server may invalidate thousands of client connections. The enterprise application managing
the server pool can take the responsibility of cloning the sessions from one server to another
without disturbing the clients.
• Generating the GUI having many numbers of similar controls:
This is a quiet frequent scenario. One can have a form or GUI that hosts many similar controls.
In order to maintain the consistency, one needs to initialize every object to the same standard
state. This process of initialization gets repeated again and again for each control increasing the
number of lines of code. In order to optimize this part of the code, one can one have an object
of a control initialized to a standard state and then replicate the same object to create as many
controls needed.
Lecture 12
Detailed pattern study:
Decorator
Decorator Design Pattern:
Decorator design pattern, it will add additional
functionalities or behaviors to an existing object
at run-time.
2. Concrete components
the decorators have reference to the instance variable that they will decorate, in this case it is Pizza. It can be any
type of pizza, all it should be is of the type pizza. Additionally, they have their own extension of description and
cost.
How it works ?
Everything wraps up, pizza has instance of ThincrustPizza() that has its own cost and description. The next line has
“composed” Cheese and ThincrustPizza objects, Cheese class acts as a decorator for the Thincrust Pizza , so now we
have ThincrustPizza with Cheese. Same applies to greekPizza. At the end ThinCrustPizza, Cheese and Olives have been
composed. As mentioned earlier, “composition refers to containing instances of other classes that implement desired
functionality”.In our case greekPizza has contained the reference of cheesePizza that has its own functionality, also
cheesePizza has contained the reference of pizza. Thus, creating a “Thin crust Pizza with tomato sauce, cheese ,
olives”. This is how decorators work.
▪ Decorator pattern solved the class explosion problem. We did not create subclasses for every type of pizza.
▪ We can easily extend code without modifying other classes. Say, if we want Onion Pizzas with olives, we just
need to extend the Topping decorator with Onion Pizza class and compose them like we did in the above
example.
▪ We can wrap the components with any number of decorators i.e. if we want onion pizza with olives and cheese,
we simply need additional wrapping and not another subclass with this feature.
How it works ?
The idea of the Decorator Pattern is to wrap an existing
class, add other functionality to it, then expose the
same interface to the outside world. Because of this our
decorator exactly looks like the original class to the
people who are using it.
2
1
3
Lecture 13
Detailed pattern study: Chain
of Responsibility
Chain of Responsibility Design Pattern:
The Chain of Responsibility Pattern describes how we handle a single request by a chain of multiple
handler objects. The request has to be processed by only one handler object from this chain.
However, the determination of processing the request is decided by the current handler. If the
current handler object is able to process the request, then the request will be processed in the
current handler object; otherwise, the current handler object needs to shirk responsibility and push
the request to the next chain handler object. And so on and so forth until the request is processed.
when a user clicks a button, the event propagates through the chain of GUI elements that starts with the button,
goes along its containers (like forms or panels), and ends up with the main application window. The event is
processed by the first element in the chain that’s capable of handling it. This example is also noteworthy because it
shows that a chain can always be extracted from an object tree.
How it works ?
when a user clicks a button, the event
propagates through the chain of GUI
elements that starts with the button,
goes along its containers (like forms
or panels), and ends up with the main
application window. The event is
processed by the first element in the
chain that’s capable of handling it.
This example is also noteworthy
because it shows that a chain can
always be extracted from an object
tree.
Implementation
2
Lecture 14
Review class for Mid Term
Examination