Design Patterns
Summary
- History of Patterns
- Patterns Catalog
- Factory Method Pattern
- Strategy Pattern
- Other Common Patterns
- Choosing a Pattern
History of Patterns
- 1977: Christopher Alexander introduces the idea of patterns
- “Successful solutions to problems”
- 1987: Ward Cunningham and Kent Beck leverage Alexander’s idea in the context of an OO language
- 1987: Erich Gamma’s dissertation on importance of patterns and how to capture them
- 1992: Jim Coplien’s book on Advanced C++ Programming Styles and Idioms
- Gang of Four: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
- “Design Patterns: Elements of Reusable OO Software”
Patterns Catalog
- Fundamental Patterns
- Delegation
- Interface
- Proxy
- Creational Patterns
- Abstract Factory
- Factory Method
- Lazy initialization
- Singleton
- Structural Patterns
- Adapter
- Bridge
- Decorator
- Behavioral Patterns
- Chain of Responsibility
- Iterator
- Observer
- State
- Strategy
- Visitor
- Concurrency Patterns
- Active Object
- Monitor Object
- Thread Pool
Factory Method Pattern
Intent
Allows for creating objects without specifying their class, by invoking a factory method (i.e., a method whose main goal is to create class instances)
Applicability
- Class can’t anticipate the type of objects it must create
- Class wants sub-classes to specify the type of objects it creates
- Class needs control over the creation of its objects
Structure
Participants:
- Creator
- Provides interface for factory method
- Concrete Creator
- Provides actual method for creating actual object
- Product
- Object created by the factory method
Example
public class ImageReaderFactory {
public static ImageReader createImageReader(InputStream is) {
int imageType = getImageType(is);
switch (imageType) {
case ImageReaderFactory.GIF
return new GifReader(is);
case ImageReaderFactory.JPEG
return new JpegReader(is);
// ...
}
}
}
Strategy Pattern
Intent
Allows for switching between different algorithms for accomplishing a task
Applicability
- Different variants of an algorithm
- Many related classes that differ only in their behavior
Structure
Participants:
- Context
- Interface to outside world
- Algorithm/Strategy
- Common interface for the different algorithms
- Concrete Strategies
- Actual implementation of the algorithm
Other Common Patterns
- Visitor
- A way of separating an algorithm from an object on which it operates
- Decorator
- A wrapper that adds functionality to a class
- stackable
- A wrapper that adds functionality to a class
- Iterator
- Access elements of a collection without knowing the underlying representation
- Observer
- Notify dependents when object changes
- Proxy
- Surrogate controls access to another object
Choosing a Pattern
Approach
- Understand your design context
- Examine pattern catalog
- Identify and study related patterns
- Apply suitable pattern