SlideShare uma empresa Scribd logo
1 de 23
Decorator Design Pattern
A Gift Wrapper
Sameer Singh Rathoud
About presentation
This presentation will help in understanding decorator design pattern, it’s
structure and it’s implementation.
I have tried my best to explain the concept in very simple language.
The programming language used for implementation in this presentation is c#. But
any one from different programming background can easily understand the
implementation.
Definition
A decorator pattern is a design pattern that allows behavior to be added to an
object dynamically. Decorators provide a flexible alternative to sub-classing for
extending functionality.
Decorator pattern is a structural design pattern.
Problem
A car manufacturing company named “UselessCars” came newly in the market. Initially they came up
with a very basic cars with four wheels, a engine and few more basic things.
UselessCarBasic
getCost()
This is a class for our
“UselessCarBasic” with an operation
“getCost()” (will return the cost of
the car).
Problem
As the company was not able to sell the cars. They came up with few more features in the car like
“doors” and “seats”.
UselessCarBasic
getCost()
So the “UselessCars” came up with three more classes
“UselessCarWithDoor”, “UselessCarWithseats” and
“UselessCarWithDoorAndSeats” deriving from “UselessCarBasic”.
Here each derive class has implemented operation “getCost()”
Inheritance
UselessCarWithDoor
getCost()
UselessCarWithseats
getCost()
UselessCarWithDoorAndSeats
getCost()
Problem
But later the company came up with lots of other features and “UselessCars” class structure met
with the class explosion.
UselessCarBasic
getCost()
Inheritance
UselessCarWithDoor
getCost()
UselessCarWithseats
getCost()
UselessCarWithABS
getCost()
UselessCarWith
AdjustableSeat
getCost()
UselessCarWith
FogLamp
getCost()
UselessCarWithAirBag
getCost()
UselessCarWithMusicSys
getCost()
UselessCarWithDoorAndSeats
getCost()
Problem
To solve this class explosion problem the “UselessCar” has changed there structure to a single class
and added operations to add the cost of each features.
UselessCarBasic
AddDoors()
AddSeats()
AddABS()
AddLeatherSeatCovers()
AddLeatherDashBoard()
AddMusicSystem()
AddAirBags()
....
getCost()
Although this is a workable solution. But this class structure is
violating the OO design principle “open/close principle” (open
for extension and close for modification). In this class
structure, every time a new feature is getting launched
“UselessCarBasic” class will get changed (adding a function in
class for adding cost). So we need to look for a better solution
to this problem.
Solution
Inheritance
<< interface >>
UselessCar
GetCost()
UselessCarBasic
Inheritance
UselessCar
GetCost()
<< interface >>
UselessCarDecorator
GetCost()
UselessCarWithDoors
GetCost()
UselessCarWithDoors
GetCost()
UselessCarWithABS
GetCost()
UselessCarWithFogLamps
GetCost()
....
GetCost()
In this approach we have created an
interface “UselessCar” which is having
an operation “GetCost()” and created a
class “UselessCarBasic” which is
implementing “UselessCar” and defining
operation “GetCost()”. Here we have
introduced one more interface
“UselessCarDecorator” which is holding a
reference of “UselessCar” and all the
features of “UselessCar” will be
implementing this interface and
providing the definition of operation
GetCost() by adding the cost of the
feature in the cost of “UselessCarBasic”.
Motivation and Intent
• The intent of this pattern is to add additional responsibilities dynamically to an
object.
Add addition functionality or state to an individual objects at run-time. Inheritance
is not feasible because it is static and applies to an entire class.
Structure
Client
Inheritance
<< interface >>
Component
Operation ()
Operation ()
Concrete Component
Operation ()
<< interface >>
Decorator
Concrete Decorator A
Operation ()
Concrete Decorator B
Operation ()
Inheritance
state AddedBehavior ()
Component
Participants in structure
• Component (interface): is a interface for objects for which responsibilities can be added
dynamically.
• Concrete component: concrete implementation of component and will provide the object for
which responsibilities can be added at runtime.
• Decorator (interface): is a interface for additional functionality or state and maintains the
reference to component.
• Concrete decoratorA and Concrete decoratorB: are the classes defining the implementation to
decorator interface and provide the additional functionality.
• Client: The user of the decorator design pattern.
Collaborations
• Created a Component and run the Operation() on that. Added a behavior/functionality/state with
concrete component and run the operation on the decorated object, now the behavior will get
changed.
Client Concrete Component Concrete Decorator
new Concrete Component ()
ComponentObject.Operation()
new Concrete Decorator (ComponentObject)
ConcreteDecoratorObject.Operation()
Implementation (C#)
Component (Interface)
public abstract class UselessCar
{
public abstract int Cost { get; }
}
Here “UselessCar” is an abstract class with
an abstract property “Cost”. Now all the
concrete classes implementing this abstract
class will override “Cost” method.
<< interface >>
UselessCar
+ Cost ()
Implementation (C#)
Concrete Component
class UselessCarBasic: UselessCar
{
public override int Cost
{
get
{
return 1000; //Basic Car Cost
}
}
}
Here a concrete class “UselessCarBasic” is
implementing abstract class “UselessCar”
and these concrete classes is overriding
property “Cost” (giving the cost of
“UselessCarBasic”) of “UselessCar”
class.
<< interface >>
UselessCar
+ Cost ()
UselessCarBasic
Cost()
Implementation (C#)
Decorator (interface)
public abstract class UselessCarDecorator : UselessCar
{
public UselessCar uselessCarObj;
public override int Cost
{
get
{
return this.uselessCarObj.Cost;
}
}
public UselessCarDecorator(UselessCar uselessCar)
{
this.uselessCarObj = uselessCar;
}
}
Here an abstract class “UselessCarDecorator”
is implementing abstract class “UselessCar” and
these concrete classes is overriding property
“Cost” of “UselessCar” class and additionally
it is holding a reference of “UselessCar”.
<< interface >>
UselessCar
+ Cost ()
UselessCarBasic
+ Cost()
UselessCarDecorator
+ Cost()
+ UselessCar
Implementation (C#)
Concrete Decorator
class UselessCarWithDoors: UselessCarDecorator {
public UselessCarWithDoors(UselessCar uselessCar)
: base(uselessCar) {
}
public override int Cost {
get {
return uselessCarObj.Cost + 200; //Basic Car Cost + Doors cost
}
}
}
“UselessCarWithDoors”
is a concrete class
implementing abstract class
“UselessCarDecorator”
and overriding property
“Cost” of
“UselessCarDecorator”
and it is defining a constructor
expecting a parameter of type
“UselessCar” this
parameter is further passed to
the constructor of base class
(“UselesscarDecorator”).
Implementation (C#)
class UselessCarWithSeats : UselessCarDecorator {
public UselessCarWithSeats(UselessCar uselessCar)
: base(uselessCar) {
}
public override int Cost {
get {
return uselessCarObj.Cost + 150; //Basic Car Cost + Seats cost
}
}
}
Here is an another class
“UselessCarWithSeats”
implementing
“UselessCarDecorator”
and overriding property
“Cost” and it is also defining
a constructor expecting a
parameter of type
“UselessCar” this
parameter is further passed to
the constructor of base class
(“UselesscarDecorator”).
Concrete Decorator
Implementation (C#)
class UselessCarWithABS : UselessCarDecorator {
public UselessCarWithABS(UselessCar uselessCar)
: base(uselessCar) {
}
public override int Cost {
get {
return uselessCarObj.Cost + 800; //Basic Car Cost + ABS cost
}
}
}
This is one more class
“UselessCarWithABS”
implementing
“UselessCarDecorator”
and overriding property “Cost”
and it is also defining a
constructor expecting a
parameter of type
“UselessCar” this parameter
is further passed to the
constructor of base class
(“UselesscarDecorator”).
Concrete Decorator
Implementation (C#)
Client
class Client {
static void Main(string[] args) {
UselessCar uselessCar = new UselessCarBasic();
System.Console.WriteLine(uselessCar.Cost);
UselessCarWithDoors uselessCarWithDoors = new UselessCarWithDoors(uselessCar);
System.Console.WriteLine(uselessCarWithDoors.Cost);
UselessCarWithSeats uselessWithCarDoorsandSeats = new UselessCarWithSeats(uselessCarWithDoors);
System.Console.WriteLine(uselessWithCarDoorsandSeats.Cost);
UselessCarWithABS uselessCarWithABS = new UselessCarWithABS(uselessCar);
System.Console.WriteLine(uselessCarWithABS.Cost);
}
}
For using decorator design pattern the client will create an instance of “UselessCarBasic” and
can add as many features as he wants to by creating the object of features by passing the reference
of “UselessCar” and can perform operation “Cost” on those feature objects.
Implementation (C#)
Class Structure << interface >>
UselessCar
+ Cost ()
UselessCarBasic
+ Cost()
UselessCarDecorator
+ Cost()
+ UselessCar
UselessCarWithABS
+ Cost()
UselessCarWithDoors
+ Cost()
UselessCarWithSeats
+ Cost()
Inheritance
Inheritance
Client
Example and applicability
GUI framework: GUI framework can use decorator pattern for extending the functionality
dynamically.
Whenever a programmer is having a requirement where he/she has to extend the functionality at
runtime on the top of some basic functionality can opt for decorator design pattern.
References
1. Design Patterns: Elements of Reusable Object-Oriented Software
• by Ralph Johnson, John Vlissides, Richard Helm, and Erich Gamma
2. Head First Design Patterns
• Kathy Sierra, Eric Freeman, Elisabeth Freeman, Bert Bates
End of Presentation . . .

Mais conteúdo relacionado

Semelhante a Decorator design pattern (A Gift Wrapper)

Software Engineer Screening Question - OOP
Software Engineer Screening Question - OOPSoftware Engineer Screening Question - OOP
Software Engineer Screening Question - OOP
jason_scorebig
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf
ssusera587d2
 

Semelhante a Decorator design pattern (A Gift Wrapper) (20)

Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in Swift
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Patterns in PHP
Patterns in PHPPatterns in PHP
Patterns in PHP
 
Unit4_2.pdf
Unit4_2.pdfUnit4_2.pdf
Unit4_2.pdf
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
 
Software Engineer Screening Question - OOP
Software Engineer Screening Question - OOPSoftware Engineer Screening Question - OOP
Software Engineer Screening Question - OOP
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
Javascript coding-and-design-patterns
Javascript coding-and-design-patternsJavascript coding-and-design-patterns
Javascript coding-and-design-patterns
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf03-Factory Method for design patterns.pdf
03-Factory Method for design patterns.pdf
 
Create an application with ember
Create an application with ember Create an application with ember
Create an application with ember
 

Mais de Sameer Rathoud

Mais de Sameer Rathoud (7)

Platformonomics
PlatformonomicsPlatformonomics
Platformonomics
 
AreWePreparedForIoT
AreWePreparedForIoTAreWePreparedForIoT
AreWePreparedForIoT
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
 
Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Decorator design pattern (A Gift Wrapper)

  • 1. Decorator Design Pattern A Gift Wrapper Sameer Singh Rathoud
  • 2. About presentation This presentation will help in understanding decorator design pattern, it’s structure and it’s implementation. I have tried my best to explain the concept in very simple language. The programming language used for implementation in this presentation is c#. But any one from different programming background can easily understand the implementation.
  • 3. Definition A decorator pattern is a design pattern that allows behavior to be added to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality. Decorator pattern is a structural design pattern.
  • 4. Problem A car manufacturing company named “UselessCars” came newly in the market. Initially they came up with a very basic cars with four wheels, a engine and few more basic things. UselessCarBasic getCost() This is a class for our “UselessCarBasic” with an operation “getCost()” (will return the cost of the car).
  • 5. Problem As the company was not able to sell the cars. They came up with few more features in the car like “doors” and “seats”. UselessCarBasic getCost() So the “UselessCars” came up with three more classes “UselessCarWithDoor”, “UselessCarWithseats” and “UselessCarWithDoorAndSeats” deriving from “UselessCarBasic”. Here each derive class has implemented operation “getCost()” Inheritance UselessCarWithDoor getCost() UselessCarWithseats getCost() UselessCarWithDoorAndSeats getCost()
  • 6. Problem But later the company came up with lots of other features and “UselessCars” class structure met with the class explosion. UselessCarBasic getCost() Inheritance UselessCarWithDoor getCost() UselessCarWithseats getCost() UselessCarWithABS getCost() UselessCarWith AdjustableSeat getCost() UselessCarWith FogLamp getCost() UselessCarWithAirBag getCost() UselessCarWithMusicSys getCost() UselessCarWithDoorAndSeats getCost()
  • 7. Problem To solve this class explosion problem the “UselessCar” has changed there structure to a single class and added operations to add the cost of each features. UselessCarBasic AddDoors() AddSeats() AddABS() AddLeatherSeatCovers() AddLeatherDashBoard() AddMusicSystem() AddAirBags() .... getCost() Although this is a workable solution. But this class structure is violating the OO design principle “open/close principle” (open for extension and close for modification). In this class structure, every time a new feature is getting launched “UselessCarBasic” class will get changed (adding a function in class for adding cost). So we need to look for a better solution to this problem.
  • 8. Solution Inheritance << interface >> UselessCar GetCost() UselessCarBasic Inheritance UselessCar GetCost() << interface >> UselessCarDecorator GetCost() UselessCarWithDoors GetCost() UselessCarWithDoors GetCost() UselessCarWithABS GetCost() UselessCarWithFogLamps GetCost() .... GetCost() In this approach we have created an interface “UselessCar” which is having an operation “GetCost()” and created a class “UselessCarBasic” which is implementing “UselessCar” and defining operation “GetCost()”. Here we have introduced one more interface “UselessCarDecorator” which is holding a reference of “UselessCar” and all the features of “UselessCar” will be implementing this interface and providing the definition of operation GetCost() by adding the cost of the feature in the cost of “UselessCarBasic”.
  • 9. Motivation and Intent • The intent of this pattern is to add additional responsibilities dynamically to an object. Add addition functionality or state to an individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.
  • 10. Structure Client Inheritance << interface >> Component Operation () Operation () Concrete Component Operation () << interface >> Decorator Concrete Decorator A Operation () Concrete Decorator B Operation () Inheritance state AddedBehavior () Component
  • 11. Participants in structure • Component (interface): is a interface for objects for which responsibilities can be added dynamically. • Concrete component: concrete implementation of component and will provide the object for which responsibilities can be added at runtime. • Decorator (interface): is a interface for additional functionality or state and maintains the reference to component. • Concrete decoratorA and Concrete decoratorB: are the classes defining the implementation to decorator interface and provide the additional functionality. • Client: The user of the decorator design pattern.
  • 12. Collaborations • Created a Component and run the Operation() on that. Added a behavior/functionality/state with concrete component and run the operation on the decorated object, now the behavior will get changed. Client Concrete Component Concrete Decorator new Concrete Component () ComponentObject.Operation() new Concrete Decorator (ComponentObject) ConcreteDecoratorObject.Operation()
  • 13. Implementation (C#) Component (Interface) public abstract class UselessCar { public abstract int Cost { get; } } Here “UselessCar” is an abstract class with an abstract property “Cost”. Now all the concrete classes implementing this abstract class will override “Cost” method. << interface >> UselessCar + Cost ()
  • 14. Implementation (C#) Concrete Component class UselessCarBasic: UselessCar { public override int Cost { get { return 1000; //Basic Car Cost } } } Here a concrete class “UselessCarBasic” is implementing abstract class “UselessCar” and these concrete classes is overriding property “Cost” (giving the cost of “UselessCarBasic”) of “UselessCar” class. << interface >> UselessCar + Cost () UselessCarBasic Cost()
  • 15. Implementation (C#) Decorator (interface) public abstract class UselessCarDecorator : UselessCar { public UselessCar uselessCarObj; public override int Cost { get { return this.uselessCarObj.Cost; } } public UselessCarDecorator(UselessCar uselessCar) { this.uselessCarObj = uselessCar; } } Here an abstract class “UselessCarDecorator” is implementing abstract class “UselessCar” and these concrete classes is overriding property “Cost” of “UselessCar” class and additionally it is holding a reference of “UselessCar”. << interface >> UselessCar + Cost () UselessCarBasic + Cost() UselessCarDecorator + Cost() + UselessCar
  • 16. Implementation (C#) Concrete Decorator class UselessCarWithDoors: UselessCarDecorator { public UselessCarWithDoors(UselessCar uselessCar) : base(uselessCar) { } public override int Cost { get { return uselessCarObj.Cost + 200; //Basic Car Cost + Doors cost } } } “UselessCarWithDoors” is a concrete class implementing abstract class “UselessCarDecorator” and overriding property “Cost” of “UselessCarDecorator” and it is defining a constructor expecting a parameter of type “UselessCar” this parameter is further passed to the constructor of base class (“UselesscarDecorator”).
  • 17. Implementation (C#) class UselessCarWithSeats : UselessCarDecorator { public UselessCarWithSeats(UselessCar uselessCar) : base(uselessCar) { } public override int Cost { get { return uselessCarObj.Cost + 150; //Basic Car Cost + Seats cost } } } Here is an another class “UselessCarWithSeats” implementing “UselessCarDecorator” and overriding property “Cost” and it is also defining a constructor expecting a parameter of type “UselessCar” this parameter is further passed to the constructor of base class (“UselesscarDecorator”). Concrete Decorator
  • 18. Implementation (C#) class UselessCarWithABS : UselessCarDecorator { public UselessCarWithABS(UselessCar uselessCar) : base(uselessCar) { } public override int Cost { get { return uselessCarObj.Cost + 800; //Basic Car Cost + ABS cost } } } This is one more class “UselessCarWithABS” implementing “UselessCarDecorator” and overriding property “Cost” and it is also defining a constructor expecting a parameter of type “UselessCar” this parameter is further passed to the constructor of base class (“UselesscarDecorator”). Concrete Decorator
  • 19. Implementation (C#) Client class Client { static void Main(string[] args) { UselessCar uselessCar = new UselessCarBasic(); System.Console.WriteLine(uselessCar.Cost); UselessCarWithDoors uselessCarWithDoors = new UselessCarWithDoors(uselessCar); System.Console.WriteLine(uselessCarWithDoors.Cost); UselessCarWithSeats uselessWithCarDoorsandSeats = new UselessCarWithSeats(uselessCarWithDoors); System.Console.WriteLine(uselessWithCarDoorsandSeats.Cost); UselessCarWithABS uselessCarWithABS = new UselessCarWithABS(uselessCar); System.Console.WriteLine(uselessCarWithABS.Cost); } } For using decorator design pattern the client will create an instance of “UselessCarBasic” and can add as many features as he wants to by creating the object of features by passing the reference of “UselessCar” and can perform operation “Cost” on those feature objects.
  • 20. Implementation (C#) Class Structure << interface >> UselessCar + Cost () UselessCarBasic + Cost() UselessCarDecorator + Cost() + UselessCar UselessCarWithABS + Cost() UselessCarWithDoors + Cost() UselessCarWithSeats + Cost() Inheritance Inheritance Client
  • 21. Example and applicability GUI framework: GUI framework can use decorator pattern for extending the functionality dynamically. Whenever a programmer is having a requirement where he/she has to extend the functionality at runtime on the top of some basic functionality can opt for decorator design pattern.
  • 22. References 1. Design Patterns: Elements of Reusable Object-Oriented Software • by Ralph Johnson, John Vlissides, Richard Helm, and Erich Gamma 2. Head First Design Patterns • Kathy Sierra, Eric Freeman, Elisabeth Freeman, Bert Bates