1 / 16

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. Pattern categories. Architectural patterns High level: Affects a whole application or a major part of an application. Design patterns

shawna
Télécharger la présentation

Patterns in programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Patterns in programming Patterns in programming

  2. What are patterns? • Answers to common design problems. • A language used by developers • To discuss answers to design problems Patterns in programming

  3. 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

  4. 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

  5. Creational patterns • Factory method • Define an static method to create (or get) objects. • 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

  6. 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 • Logger • Logger Logger.getLogger(…) • JDBC • Connection DriverManager.getConnection(…) • Statement Connection.createStatement(…) • ResultSet Statement.executeQuery(…) • javax.net.SocketFactory / javax.net.ssl.SSLSocketFactory Patterns in programming

  7. 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 the instance 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

  8. Object pool • Idea • Reuse objects which 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

  9. Structural patterns • Composite • Compose objects into tree structures. • Decorator • Attach additional responsibilities to an object dynamically. Patterns in programming

  10. 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! • Example: CompositeRestaurantMenu Patterns in programming

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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. • Example: TemplateMethodHotDrink • 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) Patterns in programming

  16. 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 • Bob Tarr Design patterns, etc. http://userpages.umbc.edu/~tarr/ • Joshua KerievskyRefactoring to Patterns, Addison Wesley Professional 2005 • A catalog of patterns http://sourcemaking.com/design_patterns Patterns in programming

More Related