90 DesignPatterns
90 DesignPatterns
OO-Concepts
• Don’t rewrite code
• Encapsulation
• Inheritance
• Write flexible code
Design Patterns
• Time to level up!
• Necessary when the projects are large
• Course projects (possibly including CSE442)
– Small projects
– Requirements don’t change
– No design patterns needed
– Can get away without proper OO usage
• Large projects with poor design
– Do you want to refactor 10,000 lines of code?
– 100,000 lines?
Caution
• Design patterns should be used in moderation
• This is a hammer
– Not all problems are nails
Let’s learn these
• Singleton
• Observer pattern
• Decorator Pattern
• Factory Pattern
• //Command pattern
• Adapter Pattern
• State pattern
• MVC
Singleton
• There can be only one!
• When your codebase needs to share a single
object (not a single class)
• Private constructor
– What?
• Controversial
– Introduces global state
Singleton
Singleton
• No need to pass the settings in every
constructor and function call
• Can cause issues
– What if I want multiple sets of settings
concurrently?
– Panic
– Then run multiple instances of the program and
let the OS take care of it
Lazy Initialization
• Don’t create an object until it’s about to be
used
• If an object is never used, it’s never created
• Can prevent multiple instantiations
• Can greatly improve efficiency
• At least spreads out the computation
– If that’s what you’re into
Observer Pattern
• A single object has many other objects that
need to know when it updates
• On an update, broadcast to all concerned
objects
• But how?
• Thermostat temp sensor
– Furnace
– AC
– Mobile app
Observer Pattern
Observer Pattern
• Loose coupling
• Observers can be registered and unregistered
during runtime
– Flexible
– Dynamic
• No need to hardcode and notify every
possible object that might ever be concerned
• Subject is only coded once
– This is a big deal!
Scenario
• Inspired from Head First Design Patterns
• Need to compute the cost of a burger
• Condiments cost extra
Burger $1.50
Ketchup $0.05
Relish $0.10
Cheese $0.50
Scenario
• How do we adjust to added requirement?
Burger $1.50
Ketchup $0.05
Relish $0.10
Cheese $0.25
Bacon $0.50
Scenario
• Customer orders double cheese and triple
bacon
Decorator Pattern
• Wrapper classes
• Add features by adding wrapper classes
• Outer object interacts with the world
• Original/inner object is hidden
• Especially useful when original class is in a
library and lacks needed funtionality
Decorator Pattern
Decorator Pattern
Food Item
cost()
Condiment
Burger
-Food Item
cost()
cost()