What are patterns? Design Patterns Lecture 10: OOP, autumn 2003 Many recurring problems are solved in similar ways This wisdom is collected into patterns design patterns - about software design Other kinds - analysis, organization, etc. patterns General definitions: An abstraction from a concrete form which keeps recurring in specific, non-arbitrary contexts. A recurring solution to a common problem in a given context and system of forces. A successfully recurring "best practice" that has proven itself in the "trenches". A literary format for capturing the wisdom and experience of expert designers, and communicating it to novices Antipatterns (http://www.antipatterns.com/) - negative experience what doesn t work and why Already familiar with: iterators, template methods 2 Design patterns Based on OO principles - inheritance & the substitution principle Goals Improve performance, code quality Provide a common vocabulary for developers Danger: can increase complexity if misused Kinds of patterns Creational - ways to create objects Structural - ways to combine classes & objects into structures Behavioral - communication between objects Pattern structure (simplified) Problem - statement of the problem and intent of the solution Forces - the kinds of criteria that justify designs and implementations (correctness, performance, space usage, modularity, extensibility, maintainability) Solution - static structure & dynamic behavior Creational patterns Factory method Abstract factory In Liskov: factory classes and factory objects Singleton 3 4 The factory pattern Factory pattern structure Dependencies on constructors => class dependencies Need to hide actual object class e.g. abstract collections vs. implementation use factory methods that produce the right objects Example: iterators create generator objects hide actual class of generators (assume only Iterator interface) Using code becomes simpler independent of actual class => more modular and maintainable 5 6
Factory pattern example The abstract factory pattern public class Set { private Object[] contents; public Iterator iterator() { return new SetIterator(); private class SetIterator implements Iterator { long currentindex = 0; public boolean hasnext() { public Object next() { public class Client { public somemethod(set s) { Iterator it = s.iterator(); while(it.hasnext()) { // do something Client Iterator next() hasnext() <<implements>> SetIterator (from Set) <<creates>> Set iterator() 7 need to produce objects from a set of compatible classes Examples: Different GUI look&feel (Motif vs. Windows) Different database storage (memory vs. disk) Different communication protocols provide one abstract factory class with many factory methods factory subclasses provide specific implementations client code uses specific factory objects factory subclasses produce objects of consistent classes Benefits: simplify using code independence from actual object classes avoid errors when creating objects 8 Abstract factory pattern structure Abstract factory pattern example abstract class Window { class MotifWindow extends Window { class AWTWindow extends Window { abstract class Scrollbar { class MotifScrollBar extends Scrollbar { class AWTScrollBar extends Scrollbar { abstract class WidgetFactory { public static WidgetFactory getwidgetfactory(); Window createwindow( ); ScrollBar createscrollbar( ); class MotifWidgetFactory implements WidgetFactory { class AWTWidgetFactory implements WidgetFactory { 9 10 When to use factories The singleton pattern NOT when just reimplementing a type When multiple implementations of a type When sets of classes provide different versions of the same code Use abstract factories to reduce dependency on factory classes 11 Problem at most one object per type class objects are not convenient Examples Single database connection Single root window Benefits Improve performance Reduce errors Potential mistakes Use directly the static method Implement by static class // Example public class DBConnection { private static DBConnection conn; private DBConnection(); public getdbconnection( ) { if (conn == null) { conn = new DBConnection(); return conn; 12
Structural patterns Flyweights Proxy Adapter Composite The flyweight pattern Many instances of identical objects Constructors always produce new objects Need to reduce storage Example: many copies of the same string (e.g. in a document) many font objects Flyweights must be immutable Enough shared objects to justify overhead Use one flyweight object to represent all identical instances Use a factory (method/class) to produce flyweights 13 14 Flyweight pattern structure The proxy pattern FlyweightFactory creates and manages flyweight objects ConcreteFlyweight implements the Flyweight interface and adds storage for the intrinsic state, if any Intrinsic data makes the instance unique Extrinsic data is the information passed in as arguments in method calls The Client references the Flyweight object Provides a surrogate for the real object Useful when the real object needs protection (e.g. limited access user access to a proxy) is a remote object (e.g. RMI) lacks some good-to-have actions ( smart reference, e.g. load at first access) The proxy knows about the real object and implements the same interface 15 16 Adaptor Converts the interface of one class into another interface Lets classes work together that couldn't otherwise because of incompatible interfaces The composite pattern Problem Nested structure All objects belong to the same type hierarchy Component and leaf nodes Examples User interfaces - GUI elements Compilers - parse trees 17 18
Composite pattern structure Behavioral patterns For traversal of composites Interpreter Visitor Control abstraction Observer 19 20 The interpreter pattern Interpreter pattern structure How to traverse a composite Apply some computation over the tree Solution Each node has a method per computation Each method calls children methods Easy to add new nodes Hard to add new computations over the whole composite 21 22 The visitor pattern Visitor pattern structure How to traverse a composite Apply some computation over the tree Composite nodes know they structure Visitors implement various algorithms Easy to add nodes Easy to add new computations More complex 23 24
The observer pattern Observer structure One change affects one or many objects. Many object behaviors depends on one object state. Need broadcast communication Decouple classes into observers and subjects 25 26