An Introduction to Patterns Robert B. France Colorado State University Robert B. France 1
What is a Pattern? Patterns are intended to capture the best available software development experiences in the form of problem-solution pairs. Software patterns concept inspired by work on patterns for building architecture carried out by Christopher Alexander. A pattern typically consists of the following A generic description of a software problem and its context factors that influence a good solution and a solution outline A process for transforming problems targeted by the pattern to solutions characterized by the pattern. Robert B. France 2
Primary Source of Patterns Gang of 4 (GoF) patterns book: Design Patterns: Elements of Reusable Object- Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Presents 23 design patterns, primarily for OO designs Focus is on patterns supporting the design for change principle Robert B. France 3
Example of a Software Development Pattern The Factory Method pattern Problem Context: Creating objects Problem: How to create objects whose representations can change or whose representation is unknown to the client object creating the object Factors: If a change is to be made to how an object is represented it should be done in one place Robert B. France 4
Solution outline Define an abstract class (or a Java interface) that contains an abstract method for creating the object i.e., localize the creation of the object The method is called a factory method Use subclasses (or classes that implement an interface) that implements the factory method i.e., the subclass provides a specific representation of the object to be created Robert B. France 5
Example Solution - 1 listcreator reference in Client object is set to a particular concrete list creator subclass when client object is created Robert B. France 6
Another Solution (no subclass variant) Example from slides on OOP review Robert B. France 7
A more complex solution example Robert B. France 8
Code fragment for CreateMaze() public Maze createmaze() { Maze amaze = makemaze(); Room r1 = makeroom(1);//each room has an id Room r2 = makeroom(2); Door door1 = makedoor(r1, r2); amaze.addroom(r1); amaze.addroom(r2); //set sides for room r1 r1.setside(north, makewall()); r1.setside(east, door1); r1.setside(south, makewall()); r1.setside(westm makewall()); //set sides for room r2 r2.setside( ); } Robert B. France 9
A more complex example - The Model- View-Controller (MVC) Pattern Problem Context: Developing user-interfaces (UIs ) Problem: How to create a UI that s resilient to changes such as changes in look-and-feel windowing system, changes in functionality. Factors: changes to UI should be easy and possible at run-time; adapting or porting the UI should not impact the implementation of the core functionality. Robert B. France 10
Solution outline: Split application into 3 areas: The Model component: encapsulates core functionality; independent of input/output data representation. The View (output) components: displays data from the model component; there can be multiple views for a single model component. The Controller (input) components: each view is associated with a controller that handles inputs; the user interacts with the system via the controller components. Robert B. France 11
Robert B. France 12
View 40 Controllers Model:increments number and displays it on the view EventHandler:activated when user changes input using the up and down keys; calls the Model to update value Model Robert B. France 13
Patterns Summary A pattern addresses a recurring software development problem that arises in a particular context, and outlines a solution for it. A pattern captures best practices in software development. A pattern should be based on actual experiences in industry Patterns provide a common vocabulary for, and understanding of best practices. Developers can refer to a pattern by name (e.g., the Adapter pattern) and others familiar with the pattern will not need further description Robert B. France 14
Pattern Types Requirements Patterns: Characterize families of requirements for a family of applications The checkin-checkout pattern can be used to obtain requirements for library systems, car rental systems, video systems, etc. Architectural Patterns: Characterize families of architectures The Broker pattern can be used to create distributed systems in which location of resources and services is transparent (e.g., the WWW) Other examples: MVC, Pipe-and-Filter, Multi-Tiered Design Patterns: Characterize families of low-level design solutions Examples are the popular Gang of Four (GoF) patterns CS314 will cover some of the simpler forms of the GoF patterns Programming idioms: Characterize programming language specific solutions Robert B. France 15
Gang of 4 (GoF) Design Pattern Classification Creational Patterns that can be used to make object creation more flexible (e.g., Factory Method) or restrict creation activities (e.g., Singleton). Help make a system independent of how objects are created, composed, and represented (i.e., allows one to vary how objects are created, composed, and represented) Structural Concerned with creating flexible mechanisms for composing objects to form larger of structures Behavioral Concerned with creating flexible algorithms and with assigning responsibilities to classes Robert B. France 16
Scope Criterion Scope determines whether a pattern applies to classes or objects Classes static relations inheritance structures Examples: Factory Method (creation); Adapter (structural); Interpreter (behavioral) Objects object relations Dynamic Examples: Abstract Factory (creation); Bridge (structural); Iterator (behavioral) Robert B. France 17
Creational Design Patterns Factory Method Abstract Factory Singleton Robert B. France 18
The Factory Method Pattern Defers object instantiation to subclasses: A factory method defines the interface of an operation that creates objects. The implementation of the operation is provided by subclasses. Abstract operation may implement a default implementation. Knowledge of what objects to create are encapsulated in subclasses. Robert B. France 19
Application/Document Example Application class manages multiple documents of different types. Contains operations for manipulating documents. Example, consider Microsoft Office which manipulates different types of documents: Word, PowerPoint, Excel, Visio documents PROBLEM: Application knows when to create documents but does not know what types of documents to create. SOLUTION: Encapsulate knowledge of creation of concrete documents in subclasses and defer implementation to these subclasses. Robert B. France 20
Factory Method Solution Robert B. France 21
Solution Structure Robert B. France 22
2 varieties Implementation Creator does not provide a default implementation: requires creation of concrete subclasses. Creator provides default implementation: subclasses can either inherit method as is or redefine it. Robert B. France 23
What design changes are accomodated? Changes to the type of products that can be created by a creator class A new subclass can be added for each type of product that is needed. Robert B. France 24
What changes are difficult to handle? One cannot add a new product to be created during run-time If the product consists of subparts one cannot vary the types of subparts used. Abstract factory pattern can be used for this purpose Robert B. France 25
Abstract Factory Pattern Context: Need to build complex objects with component parts Problem: How to isolate clients from implementation of component parts Forces: Enforce the creation of complex objects using only compatible components Robert B. France 26
Solution Structure Robert B. France 27
Robert B. France 28
Maze Game Class Model (not all operations shown) Robert B. France 29
Robert B. France 30
Maze Game with Abstract Factory Robert B. France 31
Robert B. France 32
Another Example: Canadian/European Tax Processor Robert B. France 33
Robert B. France 34
Benefits Separates clients from implementation of created objects. Product family can be changed easily. Promotes consistency among products: enforces use of compatible parts. Robert B. France 35
Drawback Difficult to introduce a new kind of product family. Interface fixes components that are to be created. Robert B. France 36
What design changes are accomodated? Can create a new product family during runtime by passing in a specialized factory. A new class of members of the family can be introduced during design by creating a factory subclass. Robert B. France 37
What changes are difficult to handle? Cannot introduce a new product family with different parts easily Interface fixes components that are to be created. Robert B. France 38
Singleton Pattern Used to ensure that only one instance of a class exists. The class keeps track of the sole instance and does not permit instantiation if an instance already exists. This is done by hiding the constructor from clients (but not the subclasses), and defining a static operation that creates an instance if and only if there are no instances. Robert B. France 39
Solution Structure Robert B. France 40
MyShapeController Factory // MyShapeControllerFactory.java // MyShapeControllerFactory uses the Factory Method design // pattern to create an appropriate instance of MyShapeController // for the given MyShape subclass. package com.deitel.advjhtp1.drawing.controller; import com.deitel.advjhtp1.drawing.model.*; import com.deitel.advjhtp1.drawing.model.shapes.*; public class MyShapeControllerFactory { // reference to Singleton MyShapeControllerFactory private static MyShapeControllerFactory factory; // MyShapeControllerFactory constructor protected MyShapeControllerFactory() {} Robert B. France 41
// return Singleton instance of MyShapeControllerFactory public static final MyShapeControllerFactory getinstance() { // if factory is null, create new MyShapeControllerFactory if ( factory == null ) { factory = new MyShapeControllerFactory(); } // end if return factory; } // end method getinstance Robert B. France 42
Structural Patterns Adapter Facade Robert B. France 43
Adapter Pattern An adapter pattern converts the interface of a class into an interface that a client expects Adapters allow incompatible classes to work together Adapters can extend the functionality of the adapted class Robert B. France 44
When to Use Need to adapt the interface of an existing class to satisfy client interface requirements Adapting Legacy Software Adapting 3 rd Party Software Robert B. France 45
Class Adapter Pattern Robert B. France 46
Object Adapter Pattern Robert B. France 47
Example -backend -acmebackend Robert B. France 48
What changes are easily accomodated? One can use components with incompatible interfaces e.g., an off-the-shelf component that has an operation that does what a client wants but has a different signature than the one used in the client; rather than edit the client, one can write an adapter in some cases the client source code may not be available and an adapter is the only solution Robert B. France 49
What changes are difficult to handle? When the adaptee provides only SOME of the functionality needed to handle a customer request, the additional functionality must be provided somewhere else (e.g., in the adapter) Robert B. France 50
Façade Pattern Provides a unified interface to a set of interfaces in a subsystem Helps to minimize communication and dependencies across subsystems Robert B. France 51
Example The SystemManager class in your assignment is a façade class A façade class is often used to manage interactions between the user interface and the services provided by software Robert B. France 52
Behavioral Patterns Iterator Pattern Observer Pattern Robert B. France 53
The Iterator Pattern Provides a uniform way to sequentially access elements of a collection regardless of the structure of the collection. Separates concerns of maintaining a collection from the concerns of traversing the collection. Robert B. France 54
Iterator Pattern Robert B. France 55
Participants The classes and/or objects participating in this pattern are: Iterator (AbstractIterator) defines an interface for accessing and traversing elements. ConcreteIterator (Iterator) implements the Iterator interface. keeps track of the current position in the traversal of the aggregate. Aggregate (AbstractCollection) defines an interface for creating an Iterator object ConcreteAggregate (Collection) implements the Iterator creation interface to return an instance of the proper ConcreteIterator Robert B. France 56
The Observer Pattern Context: A class is closely dependent on another class; a change in one requires a change in another. For example, this occurs when there is a bidirectional association between classes. Problem: How do you reduce the coupling between the 2 classes so that you can reuse and vary them Robert B. France 57
Observer Pattern Solution Two key concepts Observable (a.k.a. Subject): The class of objects whose state (e.g., values of instance variables) that will be monitored for changes Observer: The class of objects who need to be informed of changes in Observable objects Each observable object is linked to a collection of observers; if the state changes the linked observers are notified of the change Robert B. France 58
Observer Generic Solution Robert B. France 59
Observer Sequence Diagram (interaction between a subject and an observer) Robert B. France 60