160 likes | 290 Views
Patterns in programming. What are patterns?. Answers to common design problems. A language used by developers To discuss answers to design problems Note: Actually more important to understand situations than specific solutions But knowing solutions also required. Pattern categories.
E N D
Patterns in programming Patterns in programming
Patterns in programming What are patterns? • Answers to common design problems. • A language used by developers • To discuss answers to design problems • Note: Actually more important to understand situations than specific solutions • But knowing solutions also required
Patterns in programming Pattern categories • Architectural patterns • High level: Affects a whole application or a major part of an application. • Design patterns • Intermediate level: Affects a few classes. • Idioms • Low level: Affects a single class or part of a single class. • Closing a resource like a file or network connection • try { … use resource … } finally { close resource } • Testing an expected exception in JUnit try { methodThatThrowsExceptions(); fail(…); } catch (SomeException ex) { /* ignore */ }
Patterns in programming Design pattern categories • Creational patterns • How to create objects when creation requires decisions. • Structural patterns • How classes and objects are composed to form larger structures. • Behavioral patterns • Algorithms and assignment of responsibilities between objects.
Patterns in programming Creational patterns • Factory method • Define an interface for creating an object, but let subclasses decide which class to instantiate. • Singleton • Ensures a class has only one instance, and provides a global point of access to it. • Object pool • Manages the reuse of objects when a type of object is expensive to create or only a limited number of objects can be created.
Patterns in programming Factory method • Idea • Can return an instance of the specified class, or one of its subclasses • A constructor can only “return” an instance of its own class • Does not have to construct a new object • A constructor must create a new object • Can have any name • A constructor must have the same name as the class • Naming conventions • createXxx() • getXxx() • Java API usage • JDBC • Connection DriverManager.getConnection(…) • Statement Connection.createStatement(…) • ResultSet Statement.executeQuery(…) • javax.net.SocketFactory / javax.net.ssl.SSLSocketFactory
Patterns in programming Singleton • Idea • Exactly 1 instance of a class • A single global point of access for all clients • Example class A { private static A INSTANCE = new A(); // eager initialization public static A getInstance() { return INSTANCE; } private A() { … } // more methods } • Variations • Lazy initialization • The instance is not created before it is needed. • If it is never needed, it does not use resources. • getInstance method might need synchronization. • Protected constructor • Makes it possible to subclass the singleton class
Patterns in programming Object pool • Idea • Reuse of objects that are expensive to create • Usages • Thread pool • Connection pool • Connections to databases, networks, etc. • Related patterns • Singleton • The pool class is often a singleton, since the whole idea is to make all parts of an application share a single pool of objects. • Java API usage • Thread pool • Java.util.concurrent.Executors
Patterns in programming Structural patterns • Composite • Compose objects into tree structures. • Decorator • Attach additional responsibilities to an object dynamically.
Patterns in programming Composite • Idea • Recursively build composite objects from other objects. • Objects are composed at runtime using • addXx methods to add a new sub-object • removeXx methods to remove a sub-object • Object diagram looks like a tree • Composite element as root and interior nodes • Non-composite elements as leafs • Usages • Swing / AWT • Object of class Container contains other visual components. • JButton extends Container, i.e. we can add JButton’s on a JButton!
Patterns in programming Decorator • Idea • Enhancing the service provided to the user of the class. • Extend the functionality of an object – transparent to its clients. • Also known as • Wrapper • Usages • Java.io • BufferedReader decorates another reader • Java.util.Collections • Synchronized wrappers • Immutable wrappers • ReverseOrder on natural order / comparator
Patterns in programming Behavioral patterns • Observer • Define a one-to-many dependency between object so that when one object changes state, all its dependents are notified (and updated) automatically. • Strategy • Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime. • Template method • Define a skeleton of an algorithm, deferring some steps to subclasses.
Patterns in programming Observer • Idea • Decouples otherwise dependent classes. • Observers register with an observable class. • When something happens (like change of state) in the observable, all observers are notified. • Usage • Swing / AWT • Visual components send events to listeners. • JavaBeans • Components sends property change events to listeners. • Logging • Logger sends messages to handlers. • Variations • Data is sent with the notification. • Notification does not contain data. Data is fetched from the observable using get-methods.
Patterns in programming Strategy • Idea • Encapsulate (part of) an algorithm in an interface. • The algorithm may be changed at runtime. • Usages • Logging java.util.logging • Handlers have a Filter and a Formatter • Handler.setFilter(Filter filter) • Handler.setFormatter(Formatter formatter) • Related patterns • Template method • Alternative to strategy
Patterns in programming Template method • Idea • Encapsulate part of an algorithm in an abstract method implemented by subclasses. • Example abstract class SuperClass { abstract protected T doPartOfSomething(); public void doSomething() { …doPartOfSomething(); … } } class SubClass1 extends SuperClass { protected T doPartOfSomething() { … } } • Usage • Often used in frameworks • Users of the framework are supposed to extend the abstract classes. • Related patterns • Strategy • Modifies the logic / algorithm of individual objects (specified at run-time) • Template method modifies the logic of an entire class (specified at compile-time)
References • Gamma et al.Design Patterns, Addison Wesley 1994 • First book on design patterns. • Examples in C++ and Smalltalk. • Written by the so-called “Gang of Four” (GoF) • Buschmann et al.Pattern-Oriented Software Architecture, Volume 1, Wiley 1996 • Mark GrandDesign Patterns in Java, Volume 1 2nd edition, Wiley 2002 • Freeman & FreemanHead first design patterns, O’Reilly 2004 • Joshua KerievskyRefactoring to Patterns, Addison Wesley Professional 2005 • http://www.hillside.net/ • Includes a catalog of patterns http://www.hillside.net/patterns/onlinepatterncatalog.htm Patterns in programming