Introduction to
Design Patterns
Memi Lavi
www.memilavi.com
Design Patterns:
A collection of general, reusable solutions to
common problems* in software design
* Examples:
• How to communicate between classes
• How to initialize interface implementations
• How to access data stores
• And more…
Benefits of Using Design Patterns
• Tested and used by other developers
• Make your code more readable and easy to modify
History of Design Patterns
• Introduced in 1987
• Popularized in this book:
Why Should I Care?
• Patterns are Micro-Architecture
• Always be familiar with the code!
Source: https://en.wikipedia.org/wiki/Software_design_pattern
Patterns We’ll Discuss
• Factory
• Repository
• Façade
• Command
Factory Pattern
Factory Pattern
Creating objects without specifying the exact
class of the object
Factory Pattern Motivation
• Avoid strong coupling between classes
Factory Pattern Example - Weather
New Is Glue
Factory Pattern Example - Weather
Factory Pattern Example - Weather
More Types of Factory Pattern
Factory Pattern
• Hugely popular
• Base for other patterns
• Use it to avoid strong coupling
Repository Pattern
Repository Pattern
Modules not handling the actual work with the
datastore should be oblivious to the datastore
type
Repository Pattern
• Share similarities with the Data Access Layer
• DAL is for Architects
• Repository Pattern is for Developers
Repository Pattern - Example
• Human Resources Application
• Create
• Read by ID & by Department
• UpdateName
• Delete
Repository Pattern - Example
Repository Pattern - Usage
Repository Pattern - Usage
Repository Pattern – Data Store Change
Repository Pattern
• There are more advanced implementations
• Generic classes
• Inheritance
• Extension Frameworks
• Very useful, Use it!
Façade Pattern
Façade Pattern
Creating a layer of abstraction to mask
complex actions
Façade Pattern - Example
• Banking application
• Transfer money
• Make sure accounts exist
• Make sure the first account has enough money
• Withdraw money from first account
• Deposit money in second account
• Add event in account log
Façade Pattern - Example
Façade Pattern - Usage
Command Pattern
Command Pattern
All the action’s information is encapsulated
within an object
Command Pattern - Example
• Undo mechanism
• Naïve implementation:
This is
Bad!
Command Pattern - Usage
1. ICommand Interface:
2. Command Classes:
…
Command Pattern - Usage
3. Get reference to relevant objects:
Command Pattern - Usage
4. Implement the Interface:
Command
Object
Receiver
Command Pattern - Usage
5. Implement the Undo mechanism:
Invoker
Design Patterns - Summary
• Factory
• Repository
• Façade
• Command
Design Patterns - Summary
• Design consistent, flexible, readable and easy to
maintain software
• Use only the patterns you need