CS 4240: Introduction to Design Patterns Readings: Chap. 5 of Design Patterns Explained Also, Chap....

Preview:

Citation preview

CS 4240: Introduction to Design Patterns

Readings: Chap. 5 of Design Patterns Explained Also, Chap. 6 and 7 Also, on-line info on Composite pattern (and others) at http://www.oodesign.com

Readings

Chapter 5 of our textbook Handouts on various patterns

Background, Definition

From Alexander’s work in architecture Alexander: “a solution to a problem in

context.” Design pattern: a description of a problem

that reoccurs and an outline of an approach to solving that problem Generally domain, language independent Also, analysis patterns

Design Patterns: Essential Elements Pattern name

A vocabulary of patterns is beneficial Intent Problem

When to apply the pattern, what context. How to represent, organize components Conditions to be met before using

Solution Design elements: relationships, responsibilities, collaborations A template for a solution that you implement

Consequences Results and trade-offs that result from using the pattern Needed to evaluate design alternatives

Essential Elements (con’td)

Participants and collaborators Implementation Generic Structure

Patterns Are (and Aren’t)

Name and description of a proven solution to a problem

Documentation of a design decision They’re not:

Reusable code, class libraries, etc. (At a higher level)

Do not require complex implementations Always the best solution to a given situation Simply “a good thing to do”

Describing Design Patterns The GoF defined a standard format

Generally followed Not just a UML diagram!

Pattern Format (13 sections): Pattern name and classification Intent: what’s it do? Rationale? Also known as Motivation

A scenario that illustrates a sample problem and how this patterns helps solve it.

Applicability For which situations can this be applied?

Structure Graphical representation (e.g. UML)

Pattern Format (cont’d) Participants

Classes and objects, their responsibilities Collaborations

How participants interact Consequences Implementation

Pitfalls, hints, techniques, language issues Sample code

Code fragments that illustrate the pattern Known uses

From real systems Related patterns

Similar patterns, collaborating patterns

Example 1: Singleton Pattern

Global variables are bad! Why?

We often want to use global variables! Why?

Example 1: Singleton Pattern Context: Only one instance of a class is created.

Everything in the system that needs this class interacts with that one object.

Controlling access: Make this instance accessible to all clients

Solution: The class has a static variable called theInstance (etc) The constructor is made private (or protected) Clients call a public operation getInstance() that returns the

one instance This may construct the instance the very first time or be given

an initializer

Singleton: Java implementation

public class MySingleton {

private static MySingleton theInstance =

new MySingleton();

private MySingleton() { // constructor

}

public static MySingleton getInstance() {

return theInstance;

}

}

Static Factory Methods

Singleton patterns uses a static factory method Factory: something that creates an instance

Advantages over a public constructor They have names. Example:

BigInteger(int, int, random) vs.BigInteger.probablePrime()

Might need more than one constructor with same/similar signatures

Can return objects of a subtype (if needed) Wrapper class example:

Double d1 = Double .valueOf(“3.14”); Double d2 = new Double (“3.14”);

More info: Bloch’s Effective Java

Examples from Java Library

In Swing, you can create a Border and add it to a componentBorder b =

BorderFactory.createBevelBorder(3); Need the exact same border again? The above method doesn’t create a new

one. Just gives you the same one Note: works because the bevel is

immutable

Example from the Java Library

Java can manipulate its own class definitions

Example:Class classObj =

Class.forName(“edu.uva.cs441.MyClass”); Then we can do things to the Class

object What if we call this again? Only one Class object per Java-class

Example #2: PlayLists and Songs

We saw this in CS201 (maybe)

Could PlayLists “Nest”?

Could a PlayList contain Songs and other PlayLists?

This is the “Composite Design Pattern” Make PlayList contain

A list of PlayableItems, not Songs PlayList.play() calls play() on each item Polymorphism at work

Class Diagram for This Composite

General Class Diagram

Could be many Leaf classes

Polymorphism in Action

Playlist contains a list of PlayableItems PlayList.play() calls play() on each item

for (int i=0; i<list.size(); ++i) { ( (PlayableItem) list.get(i) ).play(); }

Will call the Song.play() or PlayList.play() depending on what item i really is Review question: why is the cast needed?

Façade Pattern Intent:

Simplify interface to set of interfaces in an existing subsystem.Or, need to define new/variant interface

Problem: Only need part of a complex system.

Or, need to interact in a particular way. Participants, collaborators:

Façade class, subsystem classes, client class

Façade Pattern (cont’d)

Consequences: Certain subsystem operations may not be

available in the façade Clients may “go around” the facade

Note in textbook

Reduce coupling for client Existing interfaces requires client to

access many objects to carry out task Façade object may be one object that’s a

“gateway” to multiple objects In other words: the Façade encapsulates

the system Another motto: find what varies and

encapsulate it

Examples:

Java’s URL class Really hides a set of objects and methods But not easy to see that it does this IMHO

An example from our recent CS1110 textbook Make I/O easier for beginners Class StdIn: static methods to read Class In: create object to read from

keyboard, file or URL

Class In from Princeton course textSee Javadoc here:

http://www.cs.princeton.edu/introcs/stdlib/javadoc/In.html

Encapsulate Scanner, simplify methods

public final class In { private Scanner scanner;

...

public In() { scanner = new Scanner(

new BufferedInputStream(System.in), charsetName); scanner.useLocale(usLocale); }

... /** * Is the input stream empty? */ public boolean isEmpty() { return !scanner.hasNext(); }

Create “reader” from filename or URL public In(String s) { try { // first try to read file from local file system File file = new File(s); if (file.exists()) { scanner = new Scanner(file, charsetName); scanner.useLocale(usLocale); return; } // next try for files included in jar URL url = getClass().getResource(s); // or URL from web if (url == null) { url = new URL(s); } URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(

new BufferedInputStream(is), charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println("Could not open " + s); } }

Think About and Discuss

Façade: any relation to the Law of Demeter?

“Principle of Least Knowledge” Talk only your immediate friends

Adaptor Pattern Intent:

Make an existing object match an existing interface that it doesn’t match

Problem: Existing component has right functionality but

doesn’t match the interface used Interface here? Abstract class (or Java-interface)

used polymorphically Solution:

Wrapper class with delegation etc. Two flavors: Object Adaptor vs. Class Adaptor

Adaptor Pattern (cont’d) Participants and Collaborators

Adapter class: “new” interface for… Adaptee class (existing class) Target: the needed interface Client who uses objects of type Target

Consequences: The good: solves problem and meets

intent above! Some other wrinkles…

Class Diagram for Object Adaptor

Object Adaptor pattern Note that Adapter is an

example of a “wrapper class” A common implementation technique

used in several design patterns

Book’s Example

Abstract class (or interface) Shape Methods include: display(), fill() Our code relies on Shape hierarchy and

polymorphism We need a Circle class

Sweet! Another one exists! XXCircle Bummer! Method names are different

Solution: see book or notes on board

Class Adaptor Pattern

Don’t create a separate object that wraps the existing object

Instead, create new class that Includes what existing class has (inherit) Also meets Target interface

With a Java interface, or multiple inheritance in other languages

Class Adaptor example

Problem: Existing code has a CommandBuffer class Doesn’t have an Iterator You have code that could do great things if

only you could use CommandBuffer as if it were Iterable

Example of Class Adaptor pattern

The new class implements Iterator methods in terms of getCommand() etc defined in existing class

No pair of objects: just an instance of new class

Think About and Discuss

Class adaptors are different than object adaptors

Does this difference relate to a “rule” or “principle” of OO design we’ve seen?

Comparing Façade and Adaptor Similarities:

Both designed to help us use existing classes better

Both can use wrapper objects Similar implementation solves different problems

Adaptor: existing interface we must design to (not for Façade) New object used polymorphically

Façade: need simpler interface (not a goal for Adaptor)

See table 7-1 on page 110

Summary of Intro to Design Patterns Understand background, general

principles of design patterns Examples:

Singleton Composite Façade Adaptor

Recognize them, apply them in simple situations

Exercise: Can you Adapt?

Deprecated Java interface Enumerator hasMoreElements() nextElement()

Replaced by interface Iterator hasNext() next() remove()

Your task

Create a class: EnumerationIterator This let us design and write new code

that works with Iterators, andalso interact with legacy code that exposes Enumerators for use to use

First question: class or object adaptor?

Questions to Answer

Question: which classes play which roles in the design pattern? Write this down.

Final question: write Java class with constructor and next() and hasNext().

Recommended