Patterns COM379 University of Sunderland James Malone.

28
Patterns COM379 University of Sunderland James Malone

Transcript of Patterns COM379 University of Sunderland James Malone.

Page 1: Patterns COM379 University of Sunderland James Malone.

Patterns

COM379

University of Sunderland

James Malone

Page 2: Patterns COM379 University of Sunderland James Malone.

Resources

Gamma, et al., 1995, Design Patterns, Addison-Wesley.

http://www.patterndepot.com/put/8/JavaPatterns.htm (a free download, and the code is also available!)

Page 3: Patterns COM379 University of Sunderland James Malone.

Introduction to Patterns •The recurring aspects of designs are called design patterns. – A pattern is the outline of a reusable solution to a general problem

encountered in a particular context

– Many of them have been systematically documented for all software developers to use

– A good pattern should• Be as general as possible

• Contain a solution that has been proven to effectively solve the problem in the indicated context.

Studying patterns is an effective way to learn from the experience of others

Page 4: Patterns COM379 University of Sunderland James Malone.

Pattern descriptionContext:

• The general situation in which the pattern applies

Problem: • A short sentence or two raising the main difficulty.

Forces: • The issues or concerns to consider when solving the problem

Solution: • The recommended way to solve the problem in the given context.

— ‘to balance the forces’

Antipatterns: (Optional)• Solutions that are inferior or do not work in this context.

Related patterns: (Optional) • Patterns that are similar to this pattern.

References:• Who developed or inspired the pattern.

Page 5: Patterns COM379 University of Sunderland James Malone.

Creational Patterns

• Factory Method

• Singleton

Page 6: Patterns COM379 University of Sunderland James Malone.

Factory Method

• You need an object, but which subtype of the object needs to be decided later. This can be a particularly problem during initialization, as it means the file/object loader has to know every possible subclass.

• The solution to this is called the ‘factory method’ or ‘object factory’.

• Positives:– Flexibility– Can connect parallel class hierarchies

• Negatives:– Forces subclassing of the base class

Page 7: Patterns COM379 University of Sunderland James Malone.

Example Factory Method• A database class wants an Employ object

but does not need or want details of all possible subclasses of Employ

Engineer Director

Employ

Factory DatabasegetClass

Page 8: Patterns COM379 University of Sunderland James Malone.

Singleton (Creation or Non-Creation Pattern?)

• Ensures a class has a globally accessible unique instance.• The use of a public constructor cannot guarantee that no more than

one instance will be created. • The singleton instance must also be accessible to all classes that

require it• Sometimes you need a class with only one instance, and sometimes you

need global access to a class. • Positives:

– Avoids the need to link objects at system initialization.– Sometimes you need it badly.– Supports persistence. The local copy can be a proxy for a copy kept on disk.– Reduced name space pollution.– Can be modified to support multiple instances using a Map.

• Negatives:– Has to be carefully implemented.– Sometimes it’s just not useful.

Page 9: Patterns COM379 University of Sunderland James Malone.

Singleton

–Solution:

Company

theCompany

Company «private»getInstance

if (theCompany==null) theCompany= new Company();

return theCompany;

«Singleton»

theInstance

getInstance

getInstance method

Page 10: Patterns COM379 University of Sunderland James Malone.

Structural Patterns

• Adapter• Flyweight• Proxy• MVC (discussed earlier)

Page 11: Patterns COM379 University of Sunderland James Malone.

Adapter (or Wrapper)• This pattern is basically how ‘glue code’ is written to convert one interface to

another, allowing unrelated classes to work together.• Two approaches:

– Inheritance (class adapter)—the adapter inherits from the nonconforming one and adds the methods we need to make the new derived class match the desired interface.

– Object composition by reference to implementation (object adapter)—the adapter contains an instance of the class providing the function. The reference can be to a common superclass, allowing the adapter to adapt multiple subclasses (like a wrapper around the old class).

• Positives– Already used in Java

• Negatives– A class adapter creates a concrete subclass and cannot handle subclasses of the

original class.– An object adapter makes it hard to override the object subclass behavior.

Page 12: Patterns COM379 University of Sunderland James Malone.

The Adapter Pattern–Context:

• You are building an inheritance hierarchy and want to incorporate it into an existing class.

• The reused class is also often already part of its own inheritance hierarchy.

– Problem: • How to obtain the power of polymorphism when reusing a class whose

methods– have the same function– but not the same signature

as the other methods in the hierarchy?

– Forces: • You do not have access to multiple inheritance or you do not want to use

it.

Page 13: Patterns COM379 University of Sunderland James Malone.

Adapter–Solution:

«Adaptee»

adaptedMethod

«Superclass»

polymorphicMethod

«Adapter»

polymorphicMethod()

return adaptee.adaptedMethod();

{

}

Page 14: Patterns COM379 University of Sunderland James Malone.

Adapter•Example:

ImportedCircle

calcArea

Shape

area

Square Circle

Client

Page 15: Patterns COM379 University of Sunderland James Malone.

Flyweight• Use sharing to support large numbers of fine-grained objects efficiently. E.g.,

the characters and other images on a screen need not individually contain all the data needed to draw them. Similarly, in C#, where there are no primitive types, the overhead to generate individual numbers as objects, can be overwhelming.

• Approach:– Create sharable instances of a class that are allocated when needed. Either create a

basic pool at initialization or as needed. Note that this approach can be used for complex objects as well.

• Positives:– Avoids overhead.– Saves storage.– Useful with databases.– Often combined with the composite pattern.

• Negatives:– Hard to do in Java.

Page 16: Patterns COM379 University of Sunderland James Malone.

Flyweight Example

• Suppose we want to draw a small folder icon with a name under it foreach person in a an organization. If this is a large organization, there could be a large number of such icons, but they are actually all the same graphicalimage. Even if we have two icons, one for “is Selected” and one for “notSelected” the number of different icons is small. In such a system, having anicon object for each person, with its own coordinates, name and selected state is a waste of resources.

• Instead, we’ll create a FolderFactory that returns either the selected orthe unselected folder drawing class, but does not create additional instancesonce one of each has been created. Since this is such a simple case, we justcreate them both at the outset and then return one or the other:

Page 17: Patterns COM379 University of Sunderland James Malone.

Proxy

• Allows you to represent a complex object with a simpler or more accessible one. May support copy on write for large objects that may or may not change. There are a number of useful applications.

• Approach:– Define a proxy class with the same method signatures as the complex

class. Those methods provide the proxy access to the complex class object.

• Positives:– Provides remote access, virtual access, protected access, or smart access.

• Negatives:– Non-trivial to implement.

– Overhead and delayed access.

Page 18: Patterns COM379 University of Sunderland James Malone.

The Proxy Pattern– Context:

• Often, it is time-consuming and complicated to create instances of a class (heavyweight classes).

• There is a time delay and a complex mechanism involved in creating the object in memory

–Problem: • How to reduce the need to create instances of a heavyweight class?

–Forces: • We want all the objects in a domain model to be available for programs

to use when they execute a system’s various responsibilities. • It is also important for many objects to persist from run to run of the

same program

Page 19: Patterns COM379 University of Sunderland James Malone.

Proxy

–Solution:«interface»«ClassIF»

* ******«Client» «HeavyWeight»«Proxy»

Page 20: Patterns COM379 University of Sunderland James Malone.

Proxy

•Example: «interface»ListIF

The list elements will be loaded into local memory only when needed.

ListProxy PersistentList

«interface»Student

PersistentStudentStudentProxy

Page 21: Patterns COM379 University of Sunderland James Malone.

Model-View-Controller(MVC)

• In the MVC pattern, the model and theview are strictly kept apart from each other

• Their interaction is mediated by thecontroller component: the glue that bindsthem together

• MVC consists of three kinds of objects:– Model – the application object– View – UI (screen presentation)– Controller – defines the way the UI reacts to user

inputs

Page 22: Patterns COM379 University of Sunderland James Malone.

ISubjectManager(from model)

<<Interface>>

StorageSubject(from model)

IObserver

update()

(from view)

<<Interface>>BasicSubject

notify()

(from model)

0..n0..n

-observers

IControllerStrategy(from controller)

<<Interface>>

ISubjectState(from model)

<<Interface>>StateObserver

(from view)

11

-strategy0..10..1

-subject

ControllerStrategy(from controller)

11

-viewObject

11

-modelObject

MVC – Class Diagramcontroller

view

model

Page 23: Patterns COM379 University of Sunderland James Malone.

Behavioral Patterns

• Command

• Iterator

• Observer

• Template Method

Page 24: Patterns COM379 University of Sunderland James Malone.

Command• Encapsulate a request as an object. Supports queueing, logging,

and undo operations. The Java 1.1 event model implements this.• Approach:

– Encapsulate the request as an object.

• Positives:– Hides the private details of the request.– Commands are first class objects.– Allows priority queueing.– Supports a macro or scripting language approach.

• Negatives:– Overhead– Lots of little classes

Page 25: Patterns COM379 University of Sunderland James Malone.

Iterator

• An iterator is an object that supports the traversal of a collection. The interface between an algorithm and a collection should be an iterator. – you have seen this already in banking example

• Approach:– See the Iterator interface. Consider implementing by using inner classes.

• Positives:– Raises the level of abstraction without a major performance penalty.

• Negatives:– There are some esoteric traps to avoid if the collection is simultaneously

being modified.– Protected access– Typecasting is necessary in Java

Page 26: Patterns COM379 University of Sunderland James Malone.

Observer

• Supports separation between model and view.• Approach: see Swing – you will learn about

observable classes• Positives:

– Decouples observers from models• Negatives:

– Lack of coordination between observers. Who has responsibility?

– What sort of messages should be sent? Adapter classes may be required.

Page 27: Patterns COM379 University of Sunderland James Malone.

Observer–Solution:

WeatherViewer

* ******

Observers are notified when a new prediction is readyForecaster

Observable

«ConcreteObservable» «ConcreteObserver»

«Observable»

addObservernotifyObservers

«interface»«Observer»

update

* ****** «interface»Observer

Page 28: Patterns COM379 University of Sunderland James Malone.

Template Method

• Define the skeleton of an algorithm, but defer details to subclasses. Fundamental to Java.

• In other words, if your baseclass is an abstract class you are using the template pattern

• Approach:– Abstract classes provide this capability.

• Positives:– Normal part of OO programming.

• Negatives:– Not as powerful as in C++.