What is a Pattern?

Lecture 40: "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice" "Each pattern is a three-part rule, which expresses a relation between a certain CS 62 context, a problem, and a solution" Fall 2017 on architecture patterns Kim Bruce & Alexandra Papoutsaki "Patterns are not a complete design method; they capture important practices of existing methods and practices uncodified by conventional methods" James Coplien

What are design patterns? Elements of Design Patterns

• Pattern Name • Design pattern is a problem & solution in context • Problem statement - context where it might be • Design patterns capture software architectures and applied designs • Solution - elements of the design, their relations, - Not code reuse responsibilities, and collaborations. - Instead solution/strategy reuse - Template of solution - Sometimes interface reuse • Consequences: Results and trade-offs Example: Pattern

• Consequences: • Name: Iterator or Cursor - Support different and simultaneous traversals • Problem statement - Multiple implementations of Iterator interface How to process elements of an aggregate in an - - One traversal per Iterator instance implementation independent manner • requires coherent policy on aggregate updates • Solution - Invalidate Iterator by throwing an exception, or - Aggregate returns an instance of an implementation of Iterator interface to control iteration. - Iterator only considers elements present at the time of its creation

Goals of Patterns Taxonomy of Patterns

• To support reuse, of • Creational patterns - Successful designs - concern the process of object creation - Existing code (though less important) • Structural patterns • To facilitate software evolution - deal with the composition of classes or objects - Add new features easily, without breaking existing ones • Behavioral patterns • Design for change! - characterize the ways in which classes or objects interact • Reduce implementation dependencies between and distribute responsibility. elements of software system. Creational Patterns Structural Patterns

• Singleton • Adapter - Ensure a class only has one instance, and provide a global - Convert the interface of a class into another interface point of access to it. clients expect. Adapter lets classes work together that - Ofen used in recursively defined classes (e.g., lists & trees) where couldn't otherwise because of incompatible interfaces don’t have public constructor, just public constant defined using • Proxy private constructor Provide a surrogate or placeholder for another object to Abstract Factory - • control access to it - Provide an interface for creating families of related or • Decorator dependent objects without specifying their concrete classes. - Attach additional responsibilities to an object dynamically - Alows hiding actual constructor cal in method definition

Behavioral Patterns

• Template - Define the skeleton of an algorithm in an operation, deferring some steps to subclasses • Abstract superclass Creational Patterns • State - Allow an object to alter its behavior when its internal state changes. The object will appear to change its class • Observer - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically Abstract Factory Abstract Factory (cont.)

• Solution: • Context: - Create interface w/ operations to create new products of different kinds - System should be independent of how pieces created and represented - Multiple concrete classes implement operations to create concrete product objects. - Different families of components - Products also specified w/interface - Must be used in mutually exclusive and consistent way - Concrete classes for each interface and family of - Hide existence of different families from clients products. - Client uses only interfaces

Abstract Factory (cont.) Abstract Factory Consequences

• Isolate instance creation and handling from clients • Examples: • Can easily change look-and-feel standard - GUI Interfaces: - Reassign a global variable • Mac • Enforce consistency among products in each family • Windows XP Adding to family of products is difficult • Unix • - Have to update factory abstract class and all concrete classes

• Motivation - Want to add responsibilities/capabilities to individual objects, not to an entire class. Structural Patterns - Inheritance requires a compile-time choice of parent class. • Solution - Enclose the component in another object that adds the responsibility/capability • The enclosing object is called a decorator.

Decorator Pattern Decorator Pattern Consequences

• Advantages - fewer classes than with static inheritance • A decorator forwards requests to its encapsulated - dynamic addition/removal of decorators component and may perform additional actions before or after forwarding. - keeps root classes simple • Disadvantages • Can nest decorators recursively, allowing unlimited added responsibilities. - proliferation of run-time instances abstract Decorator must provide common interface • Can add/remove responsibilities dynamically - • Tradeoffs: - useful when components are lightweight Decorator Example

FileReader frdr= new FileReader(filename);

LineNumberReader lrdr = new LineNumberReader(frdr); Behavioral Patterns String line; line = lrdr.readLine() while (line != null){ System.out.print(lrdr.getLineNumber() + ":\t" + line); line = lrdr.readLine() }

Observer Pattern

• Solution structure • Problem - Subject is aware of its observers (dependents) - Objects that depend on a certain subject must be made - Observers are notified by the subject when something aware of when that subject changes changes, and respond as necessary • E.g. receives an , changes its local state, etc. - Examples: Java event-driven programming - These objects should not depend on the implementation • Subject details of the subject - Maintains list of observers; defines a means for notifying • They just care about how it changes, not how it’s them when something happens implemented. • Observer - Defines the means for notification (update) Observer Pattern Observer Pattern Consequences class Subject { private Observer[] observers;

public void addObserver(Observer newObs){... } • Low coupling between subject and observers

public void notifyAll(Event evt){ - Subject indifferent to its dependents; can add or remove forall obs in observers do them at runtime obs.process(this,evt)} • Support for broadcasting } • Updates may be costly class Observer { public void process(Subject sub, Event evt) { - Subject not tied to computations by observers ... code to respond to event ... } }

Visitor Pattern

• Problem: want to implement multiple analyses on • We define each analysis as a separate Visitor class the same kind of object data - Defines operations for each element of a structure Spellchecking and Hyphenating Glyphs - • A separate algorithm traverses the structure, - Generating code for and analyzing an Abstract Syntax applying a given visitor Tree (AST) in a compiler - But, like , objects must reveal their • Flawed solution: implement each analysis as a implementation to the visitor object method in each object • Separates structure traversal code from operations - Follows idea objects are responsible for themselves on the structure But many analyses will occlude the objects' main code - - Observation: object structure rarely changes, but often - Result is classes hard to maintain want to design new algorithms for processing