design patterns nelson padua-perez chau-wen tseng department of computer science university of...

28
Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Post on 19-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Design Patterns

Nelson Padua-Perez

Chau-Wen Tseng

Department of Computer Science

University of Maryland, College Park

Page 2: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Design Patterns

Descriptions of reusable solutions to common software design problems

Captures the experience of expertsRationale for design

Tradeoffs

Codifies design in reusable form

ExampleIterator pattern

Page 3: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Goals

Solve common programming challenges

Improve reliability of solution

Aid rapid software development

Useful for real-world applications

Page 4: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Observations

Design patterns are like recipes – generic solutions to expected situations

Design patterns are language independent

Recognizing when and where to use design patterns requires familiarity & experience

Design pattern libraries serve as a glossary of idioms for understanding common, but complex solutions

Page 5: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Observations (cont.)

Many design patterns may need to fit togetherDesign Patterns (by Gamma et al., a.k.a. Gang of Four, or GOF) list 23 design patterns

Around 250 common OO design patterns

Design patterns are used throughout the Java Class Libraries

Page 6: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Documentation Format

1. Motivation or context for pattern2. Prerequisites for using a pattern3. Description of program structure 4. List of participants (classes & objects)5. Collaborations (interactions) between

participants6. Consequences of using pattern (good & bad)7. Implementation techniques & issues8. Example codes9. Known uses 10. Related patterns

Page 7: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Types of Design Patterns

CreationalDeal with the best way to create objects

StructuralWays to bring together groups of objects

Behavioral Ways for objects to communicate & interact

Page 8: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Creational Patterns

1. Abstract Factory- Creates an instance of several families of classes

2. Builder - Separates object construction from its representation

3. Factory Method - Creates an instance of several derived classes

4. Prototype - A fully initialized instance to be copied or cloned

5. Singleton - A class of which only a single instance can exist

Page 9: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Structural Patterns

6. Adapter - Match interfaces of different classes

7. Bridge - Separates an object’s interface from its implementation

8. Composite - A tree structure of simple and composite objects

9. Decorator - Add responsibilities to objects dynamically

10. Façade - Single class that represents an entire subsystem

11. Flyweight - Fine-grained instance used for efficient sharing

12. Proxy - Object representing another object

Page 10: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Behavioral Patterns

13. Chain of Responsibility - A way of passing a request between a chain of objects

14. Command - Encapsulate a command request as an object

15. Interpreter - A way to include language elements in a program

16. Iterator - Sequentially access the elements of a collection

17. Mediator - Defines simplified communication between classes

18. Memento - Capture and restore an object's internal state

Page 11: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Behavioral Patterns (cont.)

19. Observer - A way of notifying change to a number of classes

20. State - Alter an object's behavior when its state changes

21. Strategy - Encapsulates an algorithm inside a class

22. Template Method - Defer the exact steps of an algorithm to a subclass

23. Visitor - Defines a new operation to a class without changing class

Page 12: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Iterator Pattern

DefinitionMove through list of objects without knowing its internal representation

Where to use & benefitsUse a standard interface to represent data objects

Uses standard iterator built in each standard collection, like List, Sort, or Map

Need to distinguish variations in the traversal of an aggregate

Page 13: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Iterator Pattern

ExampleIterator for collection

Original

Examine elements of collection directly

Using pattern

Collection provides Iterator class for examining elements in collection

Page 14: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Iterator Example

public interface Iterator { Bool hasNext(); Object next();}

Iterator it = myCollection.iterator();

while ( it.hasNext() ) { MyObj x = (MyObj) it.next(); // finds all objects … // in collection

}

Page 15: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Singleton Pattern

DefinitionOne instance of a class or value accessible globally

Where to use & benefitsEnsure unique instance by defining class final

Access to the instance only via methods provided

Page 16: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Singleton Example

public class Employee { public static final int ID = 1234; // ID is a singleton} public final class MySingleton {

// declare the unique instance of the classprivate static MySingleton uniq = new MySingleton();// private constructor only accessed from this classprivate MySingleton() { … }// return reference to unique instance of classpublic static MySingleton getInstance() { return uniq;}

}

Page 17: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Adapter Pattern

DefinitionConvert existing interfaces to new interface

Where to use & benefitsHelp match an interface

Make unrelated classes work together

Increase transparency of classes

Page 18: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Adapter Pattern

ExampleAdapter from integer Set to integer Priority Queue

Original

Integer set does not support Priority Queue

Using pattern

Adapter provides interface for using Set as Priority Queue

Add needed functionality in Adapter methods

Page 19: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Adapter Example

public interface PriorityQueue { // Priority Queue void add(Object o); int size(); Object removeSmallest();}

Page 20: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Adapter Examplepublic class PriorityQueueAdapter implements PriorityQueue { Set s; PriorityQueueAdapter(Set s) { this.s = s; } public void add(Object o) { s.add(o); } int size() { return s.size(); } public Integer removeSmallest() { Integer smallest = Integer.MAX_VALUE;

Iterator it = s.iterator(); while ( it.hasNext() ) { Integer i = it.next(); if (i.compareTo(smallest) < 0) smallest = i; } s.remove(smallest); return smallest; }}

Page 21: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Factory Pattern

DefinitionProvides an abstraction for deciding which class should be instantiated based on parameters given

Where to use & benefitsA class cannot anticipate which subclasses must be created

Separate a family of objects using shared interface

Hide concrete classes from the client

Page 22: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Factory Pattern

ExampleCar Factory produces different Car objects

Original

Different classes implement Car interface

Directly instantiate car objects

Need to modify client to change cars

Using pattern

Use carFactory class to produce car objects

Can change cars by changing carFactory

Page 23: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Factory Example

class 350Z implements Car; // fast carclass Ram implements Car; // truckclass Accord implements Car; // family carCar fast = new 350Z(); // returns fast car

public class carFactory { public static Car create(String type) { if (type.equals("fast")) return new 350Z(); if (type.equals("truck")) return new Ram(); else if (type.equals(“family”) return new Accord(); }}

Car fast = carFactory.create("fast"); // returns fast car

Page 24: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Decorator Pattern

DefinitionAttach additional responsibilities or functions to an object dynamically or statically

Where to use & benefitsProvide flexible alternative to subclassing

Add new function to an object without affecting other objects

Make responsibilities easily added and removed dynamically & transparently to the object

Page 25: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Decorator Pattern

ExamplePizza Decorator adds toppings to Pizza

Original

Pizza subclasses

Combinatorial explosion in # of subclasses

Using pattern

Pizza decorator classes add toppings to Pizza objects dynamically

Can create different combinations of toppings without modifying Pizza class

Page 26: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Decorator Example

public interface Pizza { int cost();}public class SmallPizza extends Pizza { int cost() { return 8; }}public class LargePizza extends Pizza { int cost() { return 12; }}public class PizzaDecorator implements Pizza { Pizza p; PizzaDecorator (Pizza p) { this.p = p; } int cost() { return p.cost(); }}

Page 27: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Decorator Example

public class withOlive extends PizzaDecorator { int cost() { return p.cost() + 2; }}public class withHam extends PizzaDecorator { int cost() { return p.cost() + 3; }}

Pizza HamOlivePizza = new withHam ( new withOlive ( new LargePizza() ) );

… = HamOlivePizza.cost(); // returns 12+2+3

Pizza DoubleHamPizza = new withHam ( new withHam ( new SmallPizza() ) );

… = DoubleHamPizza.cost(); // returns 8+3+3

Page 28: Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Decorator Pattern

Examples from Java I/OInterface

InputStream

Concrete subclasses

FileInputStream, ByteArrayInputStream

Decorators

BufferedInputStream, DataInputStream

Code

InputStream s = new DataInputStream( new BufferedInputStream (new FileInputStream()));