Common Themes• Code to an Interface, not an Implementation• One class == one responsibility• Favor Compostion over Inheritance• Replace branching with polymorphism• Low coupling, high cohesion
Types of Patterns• Architectural • Code o Client-Server o Adapter o Cloud o Chain-of-Command o Command• Application o Decorator o MVC o Delegate o Services o Factory o Message Queue o Flyweight o Observer• UX o Singleton o Call to Action o Strategy o Progressive o Visitor disclosure
Lets get started!
Strategy• Define a family of behaviors• Each behavior is accessed via a common interface• Client code doesnt care which behavior it uses• Behaviors can be shared across class hierarchies
Delegate• Delegator passes a request to a helper (the delegate)• Delegate handles request, passes result back• Delegator passes result back to caller
Decorator• Add behaviors to a base object dynamically• Base decorator passes through unmodified• Decorators that modify requests or responses• Decorators wrap a base object or decorator
Chain-of-Responsibility• Dispatcher calls a handler, that calls a handler...• Each handler responsible for passing to next• Stop when event is handled
Observer• Publish-subscribe• Broadcast an event, all observers catch and handle• Broadcaster doesnt care about observers
Patterns derive from each other• Delegate is based on Strategy• CoR is a string of Delegates that call each other• Decorator & Observer are CoR that always run to the end
Wrap Up• More patterns out there: Command, Facade, Pool, Mediator, Visitor, Adapter• Use this vocabulary during technical discussions• Refactor spaghetti and long-winded code• Decrease coupling, increase cohesion!
Good References• http://www.oodesign.com• Gang of Four - Gamma, Helm, Johnson, Vlissides• Head-First Design Patterns