What are ?

Design Patterns • Design pattern is a problem & solution in context • Design patterns capture software architectures With a little help from slides by Bill Pugh et al and designs at University of Maryland ! Not code reuse ! Instead solution/strategy reuse ! Sometimes interface reuse

Elements of Design Patterns Example: Pattern

• Pattern Name • Name: Iterator or Cursor • Problem statement ! context where it might be • Problem statement applied ! How to process elements of an aggregate in an • Solution ! elements of the design, their relations, implementation independent manner responsibilities, and collaborations. • Solution Template of solution ! ! Aggregate returns an instance of an implementation of • Consequences: Results and trade!o"s Iterator interface to control iteration.

Iterator Pattern Goals of Patterns

• To support reuse, of • Consequences: ! Successful designs ! Support di"erent and simultaneous traversals ! Existing code !though less important" ! Multiple implementations of Iterator interface • To facilitate software evolution ! One traversal per Iterator instance ! Add new features easily, without breaking existing • requires coherent policy on aggregate updates ones ! Invalidate Iterator by throwing an exception, or • Design for change! ! Iterator only considers elements present at the time of its creation • Reduce implementation dependencies between elements of software system. Taxonomy of Patterns Creational Patterns

• Singleton • Creational patterns ! Ensure a class only has one instance, and provide a global point of access to it. ! concern the process of object creation ! We used with BinaryTree by not having public constructor for • Structural patterns EmptyBinaryTre# ! deal with the composition of classes or objects • Abstract Factory • Behavioral patterns ! Provide an interface for creating families of related or dependent objects without specifying their concrete characterize the ways in which classes or objects ! classes. interact and distribute responsibility. ! We used something like this in Garden assignment with newPlant$% method.

Structural Patterns Behavioral Patterns

• Adapter • Template ! Convert the interface of a class into another interface ! De&ne the skeleton of an algorithm in an operation, clients expect. Adapter lets classes work together that deferring some steps to subclasses couldn#t otherwise because of incompatible interfaces • State Proxy • ! Allow an object to alter its behavior when its internal ! Provide a surrogate or placeholder for another object state changes. The object will appear to change its to control access to it class • Decorator • Observer ! Attach additional responsibilities to an object ! De&ne a one!to!many dependency between objects so dynamically that when one object changes state, all its dependents are noti&ed and updated automatically

Abstract Factory

• Context: ! System should be independent of how pieces created Creational Patterns and represented ! Di"erent families of components ! Must be used in mutually exclusive and consistent way ! Hide existence of di"erent families from clients Abstract Factory !cont." Abstract Factory !cont."

• Solution: • Examples: ! Create interface w/ operations to create new products of di"erent kinds ! GUI Interfaces: ! Multiple concrete classes implement operations to • Mac create concrete product objects. • Windows XP • Unix ! Products also speci&ed w/interface ! Garden: ! Concrete classes for each interface and family of Text version products. • • Graphical version ! Client uses only interfaces

Abstract Factory Consequences

• Isolate instance creation and handling from clients • Can easily change look!and!feel standard ! Reassign a global variable Structural Patterns • Enforce consistency among products in each family • Adding to family of products is di'cult ! Have to update factory abstract class and all concrete classes

Proxy Pattern Uses of

• Goal: • Virtual proxy: impose a lazy creation semantics, ! Prevent an object from being accessed directly by its to avoid expensive object creations when strictly clients unnecessary. !Getting image $om disk." • Solution: • Monitor proxy: impose security constraints on the original object, say by making some public ! Use an additional object, called a proxy &elds inaccessible. ! Clients access protected object only through proxy ! Proxy keeps track of status and/or location of • Remote proxy: hide the fact that an object protected object resides on a remote location. Decorator Pattern

• Motivation ! Want to add responsibilities/capabilities to individual • A decorator forwards requests to its encapsulated objects, not to an entire class. component and may perform additional actions ! Inheritance requires a compile!time choice of parent before or after forwarding. class. • Can nest decorators recursively, allowing • Solution unlimited added responsibilities. ! Enclose the component in another object that adds Can add/remove responsibilities dynamically the responsibility/capability • • The enclosing object is called a decorator.

Decorator Pattern Consequences Decorator Example

• Advantages FileReader frdr= new FileReader(filename); ! fewer classes than with static inheritance ! dynamic addition/removal of decorators LineNumberReader lrdr = new LineNumberReader(frdr); keeps root classes simple ! • Disadvantages String line;

! proliferation of run!time instances line = lrdr.readLine() ! abstract Decorator must provide common interface while (line != null){ System.out.print(lrdr.getLineNumber() + • Tradeo"s: ":\t" + line); ! useful when components are lightweight line = lrdr.readLine() }

Template Pattern

• Problem ! You#re building a reusable class ! You have a general approach to solving a problem, Behavioral Patterns ! But each subclass will do things di"erently • Solution ! Invariant parts of an algorithm in parent class ! Encapsulate variant parts in template methods ! Subclasses override template methods ! At runtime template method invokes subclass ops Observer Pattern

• Solution structure • Problem ! Subject is aware of its observers $dependents% ! Objects that depend on a certain subject must be ! Observers are noti&ed by the subject when something made aware of when that subject changes changes, and respond as necessary • E.g. receives an event, changes its local state, etc. ! Examples: Java event%driven programming ! These objects should not depend on the • Subject implementation details of the subject ! Maintains list of observers; de&nes a means for • They just care about how it changes, not how it#s notifying them when something happens implemented. • Observer ! De&nes the means for noti&cation $update%

Observer Pattern Observer Pattern Consequences class Subject { private Observer[] observers;

public void addObserver(Observer newObs){... } • Low coupling between subject and observers Subject indi"erent to its dependents; can add or public void notifyAll(Event evt){ ! remove them at runtime forall obs in observers do obs.process(this,evt)} • Support for broadcasting } • Updates may be costly class Observer { ! Subject not tied to computations by observers public void process(Subject sub, Event evt) { ... code to respond to event ... } }

State Pattern

• Problem ! An object is always in one of several known states • Encode di"erent states as objects with the same ! The state an object is in determines the behavior of interface. several methods • To change state, change the state object • Solution • Methods delegate to state object ! Could use if/case statements in each method ! Better: use dynamic dispatch State Pattern Example State Pattern Example class State1 implements State { class FSM { public static State1 instance = new State1(); State state; private State1() {} public FSM(State s) { state = s; } public State move (char c) { switch (c) { case 'a': return State2.instance; public void move(char c) { case 'b': return State1.instance; default: throw new IllegalArgumentException();} state = state.move(c); } }

public boolean accept() {return false;} public boolean accept() { } return state.accept();} class State2 implements State { } public static State2 instance = new State2(); private State2() {} public State move (char c) { public interface State { switch (c) { State move(char c); case 'a': return State1.instance; case 'b': return State1.instance; boolean accept(); default: throw new IllegalArgumentException();} } } public booleanaccept() {return true;} }

State Pattern

• Problem: want to implement multiple analyses on • Can use singletons for instances of each state the same kind of object data class ! Spellchecking and Hyphenating Glyphs ! State objects don#t encapsulate $mutable% state, so can ! Generating code for and analyzing an Abstract Syntax be shared Tree $AST% in a compiler • Easy to add new states • Flawed solution: implement each analysis as a ! New states can implement the State interface, or method in each object ! New states can extend other states ! Follows idea objects are responsible for themselves • Override only selected functions ! But many analyses will occlude the objects# main code ! Result is classes hard to maintain

Visitor Pattern Visitor Pattern

• We de&ne each analysis as a separate Visitor class ! De&nes operations for each element of a structure • A separate algorithm traverses the structure, • One class hierarchy for object structure applying a given visitor ! AST in compiler ! But, like , objects must reveal their • One class hierarchy for each operation family, implementation to the visitor object called visitors • Separates structure traversal code from ! One for typechecking, code generation, pretty printing operations on the structure in compiler ! Observation: object structure rarely changes, but often want to design new algorithms for processing Visitor Pattern Consequences Visitor Traversal Choices

• Traversal in object structure $typical% Gathers related operations into one class • ! De&ne operation that performs traversal while • Adding new analyses is easy applying visitor object to each component ! New visitor for each one • Traversal implemented in visitor itself ! Easier than modifying the object structure ! E.g., perform processing at this node, then pass visitor to children nodes. • Adding new concrete elements is di'cult • Traversal code replicated in each concrete visitor ! must add a new method to each concrete Visitor subclass ! External Iterator

Designing with Patterns Designing with Patterns

• How do you know which patterns to use? • Some design patterns are immediately useful • What if you choose the wrong pattern? ! Observer, Decorator ! I.e. your code doesn#t evolve the way you thought it • Some are not immediately useful, but you think would. they might be • What if all your work to make things extensible ! You anticipate changing things later !! prognostication via patterns never pays o"? • Recently popular philosophy: XP ! I.e. your code doesn#t change in the way you thought it would. ! Design for your immediate needs • Choosing the right pattern implies ! When needs change, redesign your code to match prognostication ! Use extensive testing to validate frequent changes