2. OMG! Patterns?
▶ About mostly used patterns
▶ Examples of usage in real life
▶ Learning by code examples
▶ Learning new language
3. Example
Beauty salon.
Salon business
Salon provides following services:
▶ Haircut
▶ Coloring
▶ Styling
4. The Objective
▶ Salon going to add list of new services
▶ Salon want to have different combinations
of services in their pricelist
▶ Salon want’s to expand for new market
and provide services for males
6. System Overview
class Salon
{
string HaircutDescription();
string StylingDescription();
string ColoringDescription();
}
8. Identifying the problems
▶ There is only one thing wrong with this
approach: everything.
▶ God class. Single responsibility principle?
Never heard about…
▶ Code duplication
▶ Hard to test
▶ #@#$&%%!!!
9. Lets do a bit of refactoring
▶ Identify common interface (if any)
▶ Apply single responsibility principle
▶ Use of old good inheritance
17. Identifying the problems
▶ Requires new class for each combination
of services
▶ Hard to extend and maintain
18. Decorator
▶ The Decorator Pattern attaches additional
responsibilities to an object dynamically.
Decorators provide a flexible alternative to
subclassing for extending functionality
22. Use of Decorators
salonService = new SalonService();
salonService = new
HaircutDecorator(salonService)
salonService = new
StylingDecorator(salonService)
salonService.getDescription()
Output:
> Salon service: Haircut, Styling
26. Where Used
▶ GUI Frameworks
BaseElement
ScrollbarBehavior(BaseElement)
ShadowBehavior(BaseElement)
▶ Streams
FileStream
GZipStream(ByteStream)
27. Pros and Cons
Pros:
+ The cure for ugly code
+ Composition over inheritance (Adds flexibility)
+ Add behavior at runtime without class modification
+ Behavior can be reused
Cons:
– Too many small classes
– Could be not obvious for other developers
(example: Java streams)
28. Books
▶ Head First Design Patterns
By Eric Freeman
▶Design Patterns : Elements of
Reusable Object-Oriented Software
By (GoF) Gamma, Helm, Johnson, Vlissides
▶ Search Google for: Design patterns
30. Questions?
OMG! Patterns. Decorator
By Max Titov
Get examples: www.maxtitov.me
https://github.com/eolexe
Get in touch: eolexe@gmail.com
Twitter: eolexe