design patterns n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Design Patterns PowerPoint Presentation
Download Presentation
Design Patterns

Loading in 2 Seconds...

play fullscreen
1 / 123

Design Patterns - PowerPoint PPT Presentation


  • 156 Views
  • Uploaded on

Design Patterns. Overview. The need to manage complexity Place of data structures and algorithms Class diagrams in UML Beyond objects to patterns Example pattern Reference: Gamma et.al . chapter 1 http://hillside.net/patterns http://www.cs.wustl.edu/~schmidt/patterns-info.html.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Design Patterns' - coby


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
overview
Overview
  • The need to manage complexity
  • Place of data structures and algorithms
  • Class diagrams in UML
  • Beyond objects to patterns
  • Example pattern
  • Reference: Gamma et.al. chapter 1
    • http://hillside.net/patterns
    • http://www.cs.wustl.edu/~schmidt/patterns-info.html

CS351 - Software Engineering (AY2004)

managing software complexity
Managing software complexity
  • There is a desperate need to be able to generate complex, reliable software.
    • increasing functionality
    • increasing machine capacity
    • decreasing software quality
  • Examples of poor software quality?

CS351 - Software Engineering (AY2004)

how can you manage complexity
How can you manage complexity?
  • Software? Filing system? Building a house?
    • structure?
    • components?
    • techniques?
    • processes?
  • Let’s concentrate on structure and see how we can manage complexity there.

CS351 - Software Engineering (AY2004)

we tend to learn programming bottom up
We tend to learn programming bottom-up
  • Start with simple values and variables
    • integers, booleans, reals
    • assignment, conditional statements, loops
  • Work up to data structures
    • sets of values in relationship
    • commonly occurring abstractions
      • arrays, linear lists, stacks, queues
      • trees, graphs
  • Examine interplay between data structures and algorithms
    • choice of data structure affects efficiency of algorithm

CS351 - Software Engineering (AY2004)

data structures and classes
Data structures and classes
  • In object-oriented terms, data structures and associated algorithms are usually described by abstract data types and encapsulated in objects or classes.
    • e.g. List, Tree, Graph, Trie, etc.
  • Get the data structures right and everything else will follow
    • How do you get the data structures right?
    • How do you get the classes right?
  • How do you get a broader view of a system? Another level of abstraction?
    • consider classes as components
  • What are good ways of combining classes?
    • combine classes to give design patterns

CS351 - Software Engineering (AY2004)

abstraction given by class diagrams
Abstraction given by class diagrams
  • Can represent classes as nodes in a graph, with edgesgiving the relationships between the classes
  • Nodes can indicate state, behaviour (, identity) of classes
    • State = attributes associated such an object (the instance variables).
    • Behaviour = operations applicable to such an object (the instance methods).
    • Identity = unique value that differentiates one object from another (usually implicit)
  • Examples
    • Bank account
    • University professor

CS351 - Software Engineering (AY2004)

nodes can indicate more detail
Nodes can indicate more detail
  • Note: included attributes do not include references to other objects – include these by associations
  • Types:
    • e.g. balance: real
    • e.g. deposit(amount: real): void
  • Access control:
    • public:+ balance: real
    • protected:# balance: real
    • private:– balance: real

CS351 - Software Engineering (AY2004)

nodes can indicate more detail1
Nodes can indicate more detail
  • Identify class variables and methods by underlining
  • Annotate special kinds of components with stereotypes
    • e.g. «constructor» BankAccount()
    • e.g. «interface» Graph

CS351 - Software Engineering (AY2004)

class relationships
Class relationships
  • Classes are related to other classes
    • a GraphBase class may implement a Graph interface
    • a GraphImp class may use NodeImp and EdgeImp classes
    • a SavingsAccount class may extend a BankAccount class
  • These relationships are drawn as arcs in the class diagram

CS351 - Software Engineering (AY2004)

edge annotations
Edge annotations
  • (Central) label indicates significance of association
    • context determines which way to read the association
    • e.g. an Edge joins two Nodes
  • End-point labels indicate roles
    • implications for implementation
  • Multiplicity indicates number of participants
    • e.g. optional: 0..1
    • e.g. zero or more: 0..*
    • e.g. one or more: 1..*

Edge

Node

1

2

edge

node

label

setLabel(lbl)

getLabel()

label

setLabel(lbl)

getLabel()

joins

CS351 - Software Engineering (AY2004)

edge annotations1
Edge annotations
  • Arrow heads indicate navigation direction
    • bidirectional navigation
    • unidirectional navigation
    • implications for implementation
  • Style of arrow:
    • e.g. inherits: A inherits B
    • e.g. implements: A implements B
    • e.g.aggregates: A aggregates B
    • e.g.composite: A is a composite of B

CS351 - Software Engineering (AY2004)

aggregates versus composites
Aggregates versus composites
  • Aggregates and composites indicate a special association
    • their use is optional
  • Aggregates indicate a part-whole relationship
  • Composites indicate a part-whole relationship where thewhole strongly owns the parts
    • Copy/delete the whole → copy/delete the parts
  • E.g. student enrolled in a degree – no aggregation
  • E.g. degree includes compulsory course – aggregation
    • not composite – courses may belong to multiple degree
  • E.g. building consists of 4 floors – composite
    • floors cannot belong to more than one building

CS351 - Software Engineering (AY2004)

specializing bankaccount
Specializing BankAccount
  • Inheritance and software reuse
    • A bank account with an overdraft facility
    • A tenured versus contract University teacher
  • Reuse state and behaviour
  • Fundamental to the provision of
  • Graphical User Interfaces.

CS351 - Software Engineering (AY2004)

relating bankaccount and customer
Relating BankAccount and Customer
  • Objects can use other objects to accomplish their tasks
    • A bank account could have an associated customer
    • The customer object could be notified about overdrafts
  • Reuse state and behaviour
  • Maintains encapsulation

CS351 - Software Engineering (AY2004)

inheritance versus composition
Inheritance versus Composition
  • Inheritance has been promoted as the reuse mechanism
  • Experience shows that composition is a cleaner mechanism
    • Inheritance hierarchies can become overly complex
    • Inheritance breaks encapsulation (at least partially)
    • Inheritance is a static compile-time mechanism, whilecomposition can be a dynamic run-time mechanism(added flexibility may be good or bad)
    • Implementation of parent will affect that of the child

CS351 - Software Engineering (AY2004)

unified modeling language uml
Unified Modeling Language (UML)
  • Previous class diagram notation is part of the UnifiedModelling Language (UML)
    • arose out of other notations: OMT, Booch, Jacobsen
  • UML also addresses other models
    • Use Case diagrams for capturing external interactions
    • State diagrams for capturing the internal class activity
    • Interaction diagrams for capturing interaction between classes
    • Sequence diagrams for capturing more detailedinteraction between classes
    • Deployment diagrams for relating software to availablehardware
    • ...

CS351 - Software Engineering (AY2004)

beyond objects
Beyond objects
  • Object-oriented software construction is not enough
    • Typical systems have a large number of objects/classes
    • Relationships between classes can be very complex
    • Becomes unmanageable
  • Consider commonly occurring sets of classes — patterns
    • E.g. contract for house sale speaks in terms of Vendors,Purchasers, Premises, Chattels, etc.
    • A set of objects is required for such a contract

CS351 - Software Engineering (AY2004)

beyond patterns
Beyond patterns
  • Patterns may not be enough to structure complex software
  • You may require a higher level view of the system
  • This leads to the topic of software architecture ...

CS351 - Software Engineering (AY2004)

e x ample t he a dapter c lass p attern
Example: the Adapter (class) pattern
  • Consider wanting to use a prebuilt component which doesnot match the interface you assumed
    • very common when you try to reuse software

CS351 - Software Engineering (AY2004)

example the adapter class example
Example: the Adapter (class) example
  • Consider supplying a bank account (as above) in terms ofan account which has a single method for changes

CS351 - Software Engineering (AY2004)

example the adapter object pattern
Example: the Adapter (object) pattern
  • Consider wanting to use a prebuilt component which doesnot match the interface you assumed
  • Adaptee is used, not inherited

CS351 - Software Engineering (AY2004)

example the adapter object pattern1
Example: the Adapter (object) pattern
  • Consider needing a bank account (as above) in terms of anaccount which has a single method for changes.

CS351 - Software Engineering (AY2004)

where next
Where next?
  • Describing and classifying patterns
  • Creational patterns for more flexible object creation
  • Reference: Gamma et.al. chapters 3-4
    • http://hillside.net/patterns
    • http://www.cs.wustl.edu/~schmidt/patterns-info.html

CS351 - Software Engineering (AY2004)

reminder
Reminder
  • Patterns capture solutions to commonly occurring problems
    • Many problems arise in the context of GUIs
    • Authors need to identify 3 distinct uses/contexts beforeclassifying the solution as a pattern
  • Patterns consist of a number of classes which interact in acertain way (to solve the problem)
  • Patterns may or may not be applicable in a given context
  • Many patterns introduce extra levels of indirection
    • Most problems in Computer Science can be solved withan extra level of indirection

CS351 - Software Engineering (AY2004)

description of patterns
Description of patterns
  • Name — succinct indication of pattern’s purpose
  • Synopsis — short description of the pattern(for experienced users)
  • Context — problem description + example problem
  • Forces — considerations leading to the solution
  • Solution — describes the general-purpose solution
  • Consequences — trade-offs and results
  • Implementation — pitfalls, hints, techniques
  • Sample code
  • Related patterns — similar sorts of situations

CS351 - Software Engineering (AY2004)

example description adapter pattern
Example description – Adapter pattern
  • Name: Adapter — Class, Object — Structural
  • Synopsis: implements an interface known to the clients viaa class which is not known to the clients
  • Context: the class interfaces derived from the design of asystem may not match the class interface available in areusable library. E.g. BankAccount class with two methodsdeposit(amount) and withdraw(amount) to be adapted to aclass Account which has a single method change(amount)which accepts positive and negative amounts.
  • Forces:
    • You want to use an existing class, and its interface doesnot match the one you need
    • You do not have the option of changing the interface ofthe existing class – maybe the source isn’t available, orthe class is part of a reusable library

CS351 - Software Engineering (AY2004)

example description adapter pattern1
Example description – Adapter pattern
  • Solution: A class adapter uses multiple inheritance to adaptone interface to another. An object adapter relies on objectcomposition:
    • Target defines the domain-specific interface that Clientuses
    • Client collaborates with objects conforming to theTarget interface
    • Adaptee defines an existing interface that needsadapting
    • Adapter adapts the interface of Adaptee to the Targetinterface

CS351 - Software Engineering (AY2004)

example the adapter class pattern
Example: the Adapter (class) pattern
  • Reuse a prebuilt class which does not match the interfaceyou assumed
    • very common when you try to reuse software

CS351 - Software Engineering (AY2004)

java line code for adapter class pattern
Java-line code for Adapter class pattern

abstract class Target // Maybe an interface

{

public abstract ResultType request();

}

class Adaptee // An existing class

{

public ResultType req()

{

} …

}

CS351 - Software Engineering (AY2004)

java line code for adapter class pattern1
Java-line code for Adapter class pattern

class Adaptor extends Target, Adaptee

{

public ResultType request()

{

return req(); // Use Adaptee version

} …

}

  • Note that Java does not support multiple inheritance
    • the above would be possible in C++, Eiffel
    • the above would be possible if Target were an interface, inwhich case Adaptor would inherit Adaptee and implementTarget

CS351 - Software Engineering (AY2004)

the adapter object pattern
The Adapter (object) pattern
  • Consider wanting to use a prebuilt component which doesnot match the interface you assumed

CS351 - Software Engineering (AY2004)

java like code for adapter object pattern
Java-like code for Adapter object pattern
  • Target and Adaptee classes as before

class Adaptor extends Target // Does not inherit Adaptee

{

Adaptee adpt = new Adaptee();

public ResultType request()

{

return adpt.req(); // Use Adaptee version

} …

}

  • Note that this works directly in Java

CS351 - Software Engineering (AY2004)

example description adapter pattern2
Example description: Adapter pattern
  • Consequences: Class and object adapters have differenttrade-offs. A class adapter
    • adapts Adaptee to Target by committing to a concreteAdapter class. As a consequence, a class adapterwon’t work when we want to adapt a class and all itssubclasses.
    • lets Adapter override some of Adaptee’s behaviour,since Adapter is a subclass of Adaptee
    • introduces only one object, and no additional pointerindirection is needed to get to the Adaptee.

CS351 - Software Engineering (AY2004)

example description adapter pattern3
Example description: Adapter pattern
  • Consequences: Class and object adapters have differenttrade-offs. An object adapter
    • lets a single Adapter work with many Adaptees, i.e. theAdaptee itself and all of its subclasses (if any). TheAdapter can also add functionality to all Adaptees atonce.
    • makes it harder to override Adaptee behaviour. It willrequire subclassing Adaptee and making Adapter referto the subclass rather than the Adaptee itself.
  • Related patterns: Facade, Proxy, Strategy

CS351 - Software Engineering (AY2004)

classification of patterns
Classification of patterns
  • There are two basic dimensions of classification
  • Scope:
    • application primarily to classes or objects?
  • Purpose:
    • creational — for creating (and deleting) objects
    • structural — for composing classes or objects
    • behavioural — interaction of classes or objects

CS351 - Software Engineering (AY2004)

example classification adapter pattern
Example classification: Adapter pattern
  • Adapter is of scope class or object
  • Adapter is of purpose structural

CS351 - Software Engineering (AY2004)

creational patterns
Creational patterns
  • These patterns provide alternatives to creation of objects byusing the new function which:
    • fixes the class of object being created
      • i.e. lacks flexibility / configurability
    • is independent of other calls to new
      • i.e. does not relate creation of different kinds of objects
  • Suppose we have a situation where a number of relatedobjects (or products) need to be created
    • e.g. set of graphical components with similar look-and-feel
    • e.g. set of bank accounts with matching audit provisions
  • A common problem!

CS351 - Software Engineering (AY2004)

abstract factory object creational
Abstract factory – object creational
  • Synopsis: Provides a way to create instances of abstractclasses from a matched set of concrete subclasses
  • Context: Consider building a GUI framework which shouldwork with multiple windowing systems (e.g. Windows, Motif,MacOS) and should provide consistent look-and-feel.
  • Forces: Use the Abstract Factory pattern when:
    • a system should be independent of how its products arecreated, composed and represented
    • a system should be configured with one of multiplefamilies of products
    • a family of related products is designed to be usedtogether, and you need to enforce this constraint
    • you want to provide a class library of products, and onlyreveal their interfaces, not their implementations

CS351 - Software Engineering (AY2004)

abstract factory object creational1
Abstract factory – object creational
  • Solution: Define an abstract factory class which hasmethods to generate the different kinds of products. (For awindowing system this could generate matched buttons,scroll bars, fields). The abstract factory is subclassed for aparticular concrete set of products
    • AbstractFactory – declares an interface for operationsthat create abstract product objects
    • ConcreteFactory – implements the operations to createconcrete product objects
    • AbstractProduct – declares an interface for a type ofproduct object
    • ConcreteProduct – implement the AbstractProductinterface
    • Client – uses only the interfaces declared byAbstractFactory and AbstractProduct classes

CS351 - Software Engineering (AY2004)

abstract factory object creational2
Abstract factory – object creational

CS351 - Software Engineering (AY2004)

abstract factory object creational3
Abstract factory – object creational
  • Consequences:
    • It isolates concrete classes
      • clients are isolated from implementation classes
      • clients manipulate instances through their abstractinterfaces
    • It makes exchanging product families easy
    • It promotes consistency among products
    • Supporting new kinds of product is difficult
      • the AbstractFactory interface fixes the set of productsthat can be created
      • extending the AbstractFactory interface will involvechanging all of the subclasses
    • The hierarchy of products is independent of the client

CS351 - Software Engineering (AY2004)

lexi consistent look and feel
Lexi: consistent look-and-feel

CS351 - Software Engineering (AY2004)

java code for abstract factory pattern
Java code for Abstract Factory pattern

abstract class Product1 // Some kind of object

{

}

abstract class Product2 // Another kind of object

{ // - related to Product1

}

abstract class AbstractFactory

{

public abstract Product1 createProduct1();

public abstract Product2 createProduct2();

}

CS351 - Software Engineering (AY2004)

java code for abstract factory pattern1
Java code for Abstract Factory pattern

class version1Product1 extends Product1 // Specific kind

{ // of Product1

}

class version1Product2 extends Product2 // Specific kind

{ // of Product2

}

class version2Product1 extends Product1 // Another kind

{ // of Product1

}

class version2Product2 extends Product2 // Another kind

{ // of Product2

}

CS351 - Software Engineering (AY2004)

java code for abstract factory pattern2
Java code for Abstract Factory pattern

class version1Factory extends AbstractFactory

{ // Factory for version1 products

public Product1 createProduct1()

{

return new version1Product1();

}

public Product2 createProduct2()

{

return new version1Product1();

}

}

  • Similarly for a class version2Factory

CS351 - Software Engineering (AY2004)

java code for abstract factory pattern3
Java code for Abstract Factory pattern

class client

{

static void main()

{

AbstractFactory fact = new version1Factory();

... fact.createProduct1() // version1 products

... fact.createProduct2()

}

}

  • With the one line fact = new version2Factory(), you would end up with version2 products

CS351 - Software Engineering (AY2004)

creational patterns1
Creational patterns
  • In the abstract factory the family of related products wasindependent of the client(s)
  • A GUI framework needs to generate related products, butthe products depend on the structure of the client classes
    • e.g. a word-processor application needs to generateword-processor documents, and word-processordocuments need to be displayed in word-processorviews
  • Solution is to define methods in the (generic) client classesto create (generic) objects
    • then override these methods in a specific application

CS351 - Software Engineering (AY2004)

sample generic application and documents
Sample: generic application and documents

CS351 - Software Engineering (AY2004)

factory method class creational
Factory method – class creational
  • Synopsis: Define an interface for creating an object, but letsubclasses decide which class to instantiate. FactoryMethod lets a class defer instantiation to subclasses
  • Context: Example is that of a GUI framework. The genericApplication class will have a method createDocument tocreate a generic document. A specific use of the frameworkfor, say, word-processing GUI would subclass the genericApplication class and override the createDocument methodto generate word-processing documents.
  • Forces: Use the Factory Method pattern when:
    • a class can’t anticipate the class of objects it mustcreate
    • a class wants its subclasses to specify the objects itcreates
    • the set of classes to be generated may be dynamic

CS351 - Software Engineering (AY2004)

factory method class creational1
Factory method – class creational
  • Solution: Use a factory method to create the instances:
    • Product (e.g. Document) – defines the interface ofobjects the factory method creates
    • ConcreteProduct (e.g. MyDocument) – implements theProduct interface
    • Creator (e.g. Application) – declares the factory methodwhich returns an object of type Product (possibly with adefault implementation); may call the factory method to create a Produce object
    • ConcreteCreator (e.g. MyApplication) – overrides thefactory method to return an instance of ConcreteProduct

CS351 - Software Engineering (AY2004)

factory method class creational2
Factory method – class creational

CS351 - Software Engineering (AY2004)

factory method class creational3
Factory method – class creational
  • Consequences:
    • It eliminates the need to bind application-specific classesinto your code. The code only deals with the Productinterface and therefore can work with any user-definedConcreteProduct classes.
    • A client will have to subclass the Creator class just tocreate a particular ConcreteProduct instance.
    • Provides hooks for subclasses to provide extendedversions of objects
    • Connects parallel class hierarchies, e.g. Application –Document versus MyApplication – MyDocument
    • The set of product classes that can be instantiated maychange dynamically

CS351 - Software Engineering (AY2004)

structural patterns
Structural patterns
  • Reference: Gamma et al.: Chapter 4.
  • These patterns allow you to achieve different relationshipsbetween classes or objects
    • Adapter is a structural pattern
  • Consider a situation where you have some recursivecomposition of objects
    • e.g. consider a document formatting program thatformats characters into lines, lines into columns,columns into pages
    • suppose that columns can contain frames which cancontain columns
    • the recursive structure can get rather complicated

CS351 - Software Engineering (AY2004)

structural patterns1
Structural patterns

CS351 - Software Engineering (AY2004)

composite object structural
Composite – object structural
  • Synopsis: Allows you to build complex objects byrecursively composing similar objects in a treelike manner,representing whole-part hierarchies
  • Context: In a document-formatting program (such asdescribed previously), the complex inclusion relationshipscan lead to complex code. This is made worse if you try tohandle primitive and container objects differently.The key to the pattern is to define an abstract class whichrepresents both primitive and composite components
  • Forces:
    • you have a complex object that needs to bedecomposed into a part-whole hierarchy
    • you want to minimise the complexity of the part-wholehierarchy by minimising the number of different kinds ofchild objects

CS351 - Software Engineering (AY2004)

composite object structural1
Composite - object structural
  • Solution: Provide an abstract superclass for all objects in thehierarchy and an abstract superclass for all composites inthe hierarchy
    • AbstractComponent – the common superclass for allobjects in the hierarchy
    • AbstractComposite – the common superclass for allcomposite objects in the hierarchy. It inherits fromAbstractComponent and has additional methods to addand remove components
    • ConcreteComponent – specific component in thehierarchy
    • ConcreteComposite – specific composite in thehierarchy

CS351 - Software Engineering (AY2004)

composite object structural2
Composite – object structural

CS351 - Software Engineering (AY2004)

composite object structural3
Composite – object structural
  • Consequences:
    • The tree-like composite object can be treated asconsisting of AbstractComponents (whether they aresimple or composite)
    • Clients of AbstractComponent can ignore whether it isactually a composite or not
    • An operation performed on an AbstractCompositetreated as an AbstractComponent can be delegated tothe component objects
    • Any AbstractComponent object can be a child of anAbstractComposite. More restrictive policies can beenforced.
  • Related patterns: Chain of responsibility

CS351 - Software Engineering (AY2004)

composite object structural4
Composite – object structural

CS351 - Software Engineering (AY2004)

glyph interface for lexi
Glyph interface for Lexi
  • All graphics, whether simple or composite, will have acommon interface of a Glyph:

interface Glyph {

void Draw(Window) // to display itself

Rect Bounds() // return the bounding rectangle

Boolean Intersects(Point) // determine if the point is in the

// bounding rectangle (and the glyph

// needs to respond to some event)

void Insert(Glyph, int) // add a component glyph

void Remove(Glyph) // remove a glyph

Glyph Child(int) // return a component glyph

Glyph Parent() // return the parent glyph

}

CS351 - Software Engineering (AY2004)

structural patterns2
Structural patterns
  • Consider a situation where you want to control access to anobject
    • e.g. a distributed system where the application needs tointeract with an object but it should not need to knowwhether the object is local or remote
    • e.g. a word processor where you do not wish to openand display a (large) image unless it is required

CS351 - Software Engineering (AY2004)

example text document with large images
Example- text document with large images

CS351 - Software Engineering (AY2004)

proxy object structural
Proxy – object structural
  • Synopsis: Provide a surrogate or placeholder for anotherobject to control access to it
  • Context: A proxy object receives method calls from clientson behalf of another object. The proxy object does notprovide the services directly but calls the methods of theobject. Proxy is applicable whenever there is a need for amore versatile or sophisticated reference to an object than asimple pointer, such as:
    • a remote proxy provides a local representative for anobject in a different address space
    • a virtual proxy creates expensive objects on demand
    • a protection proxy controls access to the original object
    • a smart reference is a replacement for a bare pointerthat performs additional actions when an object isaccessed

CS351 - Software Engineering (AY2004)

proxy object structural1
Proxy – object structural
  • Forces:
    • the service-providing object cannot provide the serviceat a convenient time and place
    • gaining visibility to an object is non-trivial and you wantto hide the complexity
    • you want to control access to the service-providingobject

CS351 - Software Engineering (AY2004)

proxy object structural2
Proxy – object structural
  • Solution: Proxy forwards requests to RealSubject whenappropriate, depending on the kind of proxy
    • Subject (e.g. Graphic) – defines the common interfacefor RealSubject and Proxy so that Proxy can be usedanywhere that RealSubject is expected
    • RealSubject (e.g. Image) – defines the real object thatthe proxy represents
    • Proxy (e.g. ImageProxy) – maintains a reference thatlets the proxy access the real subject; provides aninterface identical to Subject’s so that a proxy can besubstituted for the real subject; controls access to thereal subject

CS351 - Software Engineering (AY2004)

proxy object structural3
Proxy – object structural

CS351 - Software Engineering (AY2004)

proxy object structural4
Proxy – object structural
  • Consequences:
    • The additional level of indirection in accessing an objectcan have many uses:
      • a remote proxy can hide the fact that an objectresides in a different address space
      • a virtual proxy can perform optimisations such ascreating an object on demand
      • protection proxies and smart references allowadditional housekeeping tasks when an object isaccessed
    • A Proxy can also be used to defer duplication of a (large) object until the duplicate is actually changed (andthe copy needs to be generated)
  • Related patterns: Facade, Decorator

CS351 - Software Engineering (AY2004)

structural patterns3
Structural patterns
  • Consider a situation where you want to vary theimplementation of an abstraction at run time
    • e.g. given a fixed GraphBase you may want to vary theGraphImp at run-time (to suit particular algorithms)
  • Consider a situation where you want to allow a number ofrelated abstractions each with a number of differentimplementations
    • it is then desirable for the abstractions andimplementations to vary independently

CS351 - Software Engineering (AY2004)

example variety of windows and systems
Example – variety of windows and systems

CS351 - Software Engineering (AY2004)

bridge object structural
Bridge – object structural
  • Synopsis: Decouple an abstraction from its implementationso that they can vary independently
  • Context: You can have hierarchies of windowingabstractions and hierarchies of windowing systems. If youcombine the two, you will end up with too many classes.
  • Forces:
    • you want to avoid a permanent binding between anabstraction and its implementation
    • both the abstractions and the implementations shouldbe extensible by subclassing
    • changes in the implementation of an abstraction shouldhave no impact on clients
    • you have a proliferation of classes (as in the example)
    • you want to share an implementation among multipleobjects

CS351 - Software Engineering (AY2004)

bridge object structural1
Bridge – object structural
  • Solution: Abstractions have reference to the implementationand forward client requests as required
    • Abstraction (e.g. Window) – defines the abstraction’sinterface; maintains a reference to an object of typeImplementor
    • RefinedAbstraction (e.g. IconWindow) – extends theinterface defined by Abstraction
    • Implementor (e.g. WindowImp) – defines the interfacefor the implementation classes. This interface doesn’tneed to correspond exactly to the Abstraction’s interface(but it may)
    • ConcreteImplementor (e.g. XWindowImp) – implementsthe Implementor’s interface

CS351 - Software Engineering (AY2004)

bridge object structural2
Bridge – object structural

CS351 - Software Engineering (AY2004)

example variety of windows and systems1
Example – variety of windows and systems

CS351 - Software Engineering (AY2004)

bridge object structural3
Bridge – object structural
  • Consequences:
    • Decoupling abstraction and implementation:
      • an implementation is not bound permanently to aabstraction
      • eliminates compile-time dependencies on theimplementation, i.e. can change implementation classwithout necessarily recompiling
    • Improved extensibility:
      • the Abstraction and Implementation hierarchies canbe extended independently
    • Hiding implementation details from clients:
      • e.g. clients don’t need to know if implementations areshared
  • Related patterns: Adapter, Factory method

CS351 - Software Engineering (AY2004)

where next1
Where next?
  • Structural patterns for more flexible object relationships
    • Decorator
  • Behavioral patterns for more flexible object interaction
    • Strategy
    • Iterator
  • Reference:, Gamma et.al. chapter 5
    • http://hillside.net/patterns
    • http://www.cs.wustl.edu/~schmidt/patterns-info.html

CS351 - Software Engineering (AY2004)

structural patterns4
Structural patterns
  • Sometimes you want to add capabilities/responsibilities toan individual object and not to a whole class
    • e.g. you may want to display some objects in a GUI withembellishments like a border or drop shadow
    • e.g. you may want to add scroll bars to a componentonly when it cannot be fully displayed in the window
  • Using inheritance to add the capability means that allobjects will have the additional properties (e.g. border)
  • Another approach is to define a class to act as a filter:
    • it encloses the object to be embellished
    • it adds the capability required
    • such a filter can be added as required

CS351 - Software Engineering (AY2004)

decorator object structural
Decorator – object structural
  • Synopsis: Add functionality (dynamically) to an object in away which is transparent to its clients
  • Context: In a GUI, you may want to add and retractembellishments of displayed objects, such as a border orshading or some highlight. It is not appropriate to add thisto every displayed object, and further, you may wish toretract the embellishment without discarding the originalobject.
  • Forces:
    • You want to extend the functionality of a number ofobjects of a given class, but you do not want to add thisto every instance
    • There is a need to dynamically extend or withdraw thecapabilities of objects

CS351 - Software Engineering (AY2004)

decorator object structural1
Decorator – object structural
  • Solution: Define a class to act as a wrapper/filter for theoriginal object and which adds the necessary functionality.Such a wrapper instance can be added or removed at runtime.
    • Component — defines the interface for objects whichcan have capabilities added dynamically
    • ConcreteComponent — defines the objects to whichadditional capabilities can be attached
    • Decorator — includes the Component interface, holds areference to a component
    • ConcreteDecorator — adds the required capabilities toa Decorator

CS351 - Software Engineering (AY2004)

decorator object structural2
Decorator – object structural

CS351 - Software Engineering (AY2004)

decorator object structural3
Decorator – object structural
  • Consequences:
    • Decorator allows for dynamic change in the capabilitiesof components, by adding and removing wrappers
    • You can mix and match with a number of wrappersachieving a large number of possible combinations
    • Flexibility of wrappers makes them more error prone,e.g. using incompatible wrappers or getting circularreferences
    • Use of decorators reduces the number of classes, butincreases the number of objects (which can hinderdebugging)
    • The use of decorators makes it difficult to distinguishobjects by their object identities
  • Related patterns: Delegation, Filter, Strategy

CS351 - Software Engineering (AY2004)

behavioral patterns
Behavioral patterns
  • Consider a system that needs to break a stream of text into lines. There are many algorithms for doing this – hardwiringa particular algorithm may be undesirable:
    • clients will be more complex if they include thealgorithm
    • different algorithms will be appropriate at different timesor in different contexts
    • it is difficult to add new algorithms
  • The solution is to define classes which encapsulate differentline-breaking algorithms
    • the so-called Strategy pattern

CS351 - Software Engineering (AY2004)

strategy object behavioral
Strategy – object behavioral
  • Synopsis: Define a family of algorithms, encapsulate eachone, and make them interchangeable. Strategy lets thealgorithm vary independently from clients that use it
  • Context: In a document editor you may want to vary thechoice of line-breaking strategies, possibly on-the-fly
  • Forces: Use the Strategy pattern when:
    • many related classes differ only in their behavior, inwhich case the Strategy provides a way of configuring aclass with one of many behaviors
    • you need different variants of an algorithm
    • an algorithm uses data that clients shouldn’t know about– Strategy avoids exposing complex, algorithm-specificdata structures
    • a class defines multiple alternative behaviors

CS351 - Software Engineering (AY2004)

strategy object behavioral1
Strategy – object behavioral
  • Solution: Encapsulate the algorithm in an object:
    • Strategy (e.g. Compositor) – declares an interfacecommon to all supported algorithms. Context uses thisinterface to call the algorithms defined by aConcreteStrategy
    • ConcreteStrategy (e.g. SimpleCompositor) –implements the algorithm using the Strategy interface
    • Context (e.g. Composition) – is configured with aConcreteStrategy object, and may define an interfacethat lets Strategy access its data.

CS351 - Software Engineering (AY2004)

structural of strategy pattern
Structural of strategy pattern

CS351 - Software Engineering (AY2004)

example breaking test into lines
Example: breaking test into lines
  • Composition maintains line breaks in displayed text – it uses aCompositor to determine those line breaks
  • Compositor determines line breaks – SimpleCompositor for plaintext, TexCompositor for Tex algorithm, etc.

CS351 - Software Engineering (AY2004)

strategy object behavioral2
Strategy – object behavioral
  • Consequences: The Strategy pattern has the followingbenefits and drawbacks:
    • families of related algorithms can be defined using aclass hierarchy, thus allowing common functionality of the algorithms to be factored out
    • an alternative to subclassing for providing a variety ofalgorithms or behaviours. Subclassing for modifyingbehaviour hard-wires the behaviour into Context.Further, subclassing does not support dynamicmodification of the algorithm
    • Strategies can eliminate conditional statements used toselect the particular algorithm
    • Strategies provide a choice of implementations,depending for example, on different time and spacetradeoffs

CS351 - Software Engineering (AY2004)

strategy object behavioral3
Strategy – object behavioral
  • Consequences: The Strategy pattern has the followingbenefits and drawbacks:
    • families of related algorithms can be defined using aclass hierarchy, thus allowing common functionality ofthe algorithms to be factored out
    • an alternative to subclassing for providing a variety ofalgorithms or behaviours. Subclassing for modifyingbehaviour hard-wires the behaviour into Context.Further, subclassing does not support dynamicmodification of the algorithm
    • Strategies can eliminate conditional statements used toselect the particular algorithm
    • Strategies provide a choice of implementations,depending for example, on different time and spacetradeoffs

CS351 - Software Engineering (AY2004)

behavioral patterns1
Behavioral patterns
  • Suppose we have an aggregate data structure and we wishto access the components without revealing the structure ofthe aggregate
    • e.g. it would be nice to be able to write something like:

for (Iterator i = s.iterator() i.hasNext();) {

x=i.next();

...

    • e.g. we may have a Set data structure and wish toexamine the elements of the set without revealingwhether they are stored as an array, linked list, etc.
    • Solution is to define an Iterator

CS351 - Software Engineering (AY2004)

iterator object behavioral
Iterator – object behavioral
  • Synopsis: Provide a way to access the elements of anaggregate object sequentially without exposing itsunderlying representation
  • Context: useful for accessing the components of any datastructure, e.g. set, list, tree
  • Forces: Use the Iterator pattern:
    • to access an aggregate object’s contents withoutexposing its internal representation
    • to support multiple traversals of aggregate objects
    • to provide a uniform interface for traversing differentaggregate structures (i.e. to support polymorphiciteration)

CS351 - Software Engineering (AY2004)

iterator object behavioral1
Iterator – object behavioral
  • Solution:
    • Iterator – defines an interface for accessing andtraversing elements
    • ConcreteIterator (e.g. PTListIterator) – implements theIterator interface; keeps track of the current position inthe traversal of the aggregate
    • Aggregate – defines an interface for creating an Iteratorobject
    • ConcreteAggregate (e.g. PTList) – implements theIterator creation interface to return an instance of theproper ConcreteIterator

CS351 - Software Engineering (AY2004)

example a list iterator
Example: a list iterator
  • PTListIterator will need to have areference to the list (as indicatedby the arrow in the diagram)
  • For scoping reasons (in Java), the PTListIterator will be declaredas a public inner class of PTList—only then will the hiddencomponents of PTList be accessible to the iterator, cf. friend inC++

CS351 - Software Engineering (AY2004)

iterator object behavioral2
Iterator – object behavioral
  • Consequences: There are 3 important consequences:
    • It supports variations in the traversal of an aggregate.Complex data structures may be traversed in manyways. Different iterators can be defined for differentkinds of traversal
    • Iterators simplify the Aggregate interface. TheAggregate does not need to supply extra functions foriteration, since they are now available in a separateclass.
    • More than one traversal can be pending on anaggregate. This is because each iterator keeps track ofits own traversal state. The same effect would be moredifficult if the aggregate stored the traversal state.
    • You should query the robustness of the iterator – whathappens if the aggregate is changed during traversal?

CS351 - Software Engineering (AY2004)

java code for an iterator
Java code for an iterator
  • Code added to the PTSet class

import java.util.Iterator;

import java.util.Set;

class PTSet implements Set {// class definition

public class ElementIterator implements Iterator {

// use the Iterator interface

int currelt = 0;

public boolean hasNext() { // part of the Iterator interface

return currelt < numElements();

}

public Object next() { // part of the Iterator interface

Object result = null; // result will require coercion

if (hasNext()) {

result = item(currelt);

currelt = currelt+1;

}

return result;

}

}

public Iterator iterator() {// function to create an iterator

return new ElementIterator();

}

}

Use iterator

Interface of Java

Generate iterator

CS351 - Software Engineering (AY2004)

java code for an iterator1
Java code for an iterator
  • Code added to the client class

import java.util.Iterator;

class Client { // class definition for some client

PTSet s = new PTSet(); // will process elements of set s

for (Iterator iter = s.makeElementIterator(); iter.hasNext(); ) { // generate the iterator

Element e=(Element)iter.next();

…}

}

CS351 - Software Engineering (AY2004)

behavioral patterns2
Behavioral patterns
  • In a GUI, it is common to support undoable operations
    • you choose a graphical component and perform someoperation on it
    • After that you wish to be able to undo/redo it
  • Alternatively, you may wish to have the facility for queuing operations, or scheduling them for later execution.
  • The common way to support this functionality is with theCommand pattern

CS351 - Software Engineering (AY2004)

command object behavioral
Command – object behavioral
  • Synopsis: Encapsulates a request as an object, therebyletting you parameterise clients with different requests,queue or log requests, and support undoable operations
  • Context: support for undoable commands such as Cut,Copy and Paste in a GUI.
  • Forces: Use the Command pattern when you want to:
    • parameterise objects by an action to perform.(Commands are an object-oriented replacement forcallbacks in procedural languages.)
    • specify, queue, and execute requests at different times.The Command object can have a lifetime independentof the original request
    • support undo, since a Command can store relevantstate for reversing the effects of the command

CS351 - Software Engineering (AY2004)

command object behavioral1
Command – object behavioral
  • Forces (ctd): Use the Command pattern when you want to:
    • support logging changes so that they can be reappliedin case of a system crash
    • structure a system around high-level operations built onprimitive operations. Such a structures is common ininformation systems that support transactions. Atransaction encapsulates a set of changes to data. TheCommand pattern offers a way to model transactions.

CS351 - Software Engineering (AY2004)

command object behavioral2
Command – object behavioral
  • Solution: The requested operation is encapsulated in anobject with sufficient data to be able to perform and undo it:
    • Command – declares an interface for executing anoperation
    • ConcreteCommand (e.g. PasteCommand) – defines abinding between a Receiver object and an action;implements commit() by invoking the correspondingoperation(s) on Receiver
    • Client (e.g. Application) – creates a ConcreteCommandobject and sets its Receiver
    • Invoker (e.g. MenuItem) – asks the command to carryout the request
    • Receiver (e.g. Document) – knows how to perform theoperations associated with carrying out a request

CS351 - Software Engineering (AY2004)

structure of command pattern
Structure of command pattern

CS351 - Software Engineering (AY2004)

example gui commands
Example: GUI commands

CS351 - Software Engineering (AY2004)

command object behavioral3
Command – object behavioral
  • Consequences:
    • Command decouples the object that invokes theoperation from the one that knows how to perform it
    • Commands are first-class objects – they can bemanipulated and extended like any other object
    • You can assemble commands into a compositecommand
    • You can add new commands without changing existingclasses
  • Related patterns: Strategy

CS351 - Software Engineering (AY2004)

motivating example for design patterns
Motivating example for design patterns
  • Graphical user interfaces (GUIs) are quite pervasive
    • they are complex pieces of software
    • their development relies heavily on object-orientation
  • Much of the initial motivation for design patterns arose in thecontext of GUI development
    • no coincidence that Gamma developed key GUI frameworks
    • there are common problems in the GUI context
    • there are standard solutions – design patterns
  • A GUI case study provides the context for demonstrating anumber of design patterns

CS351 - Software Engineering (AY2004)

essential features of a gui
Essential features of a GUI
  • Graphical display
    • windows
    • icons
    • menus
  • User interaction via pointing device (mouse) + keyboard
    • select window, navigate within a window
    • select object as target for operation
    • select operation via menus (or keyboard)
  • Event-driven paradigm
    • activity is determined by user interaction, notpredetermined by program

CS351 - Software Engineering (AY2004)

event driven paradigm
Event-driven paradigm
  • Typically GUI style program
    • read a graph if the user selects appropriate menu item
    • modify display of graph in response to mouse activity
    • perform analysis in response to menu item
    • produce results if requested
  • Structure of program is based around a central event loop
    • repeatedly wait for an event and then process it

CS351 - Software Engineering (AY2004)

requirements for a document editor
Requirements for a document editor
  • A significant design problem
    • What are the issues to be addressed?
    • Can we formulate the “big picture”?
    • How effective are patterns for capturing the designchoices?
  • Document editor (called Lexi) in the style of Word, etc.
    • Documents consist of text + graphics
    • Manipulate individual or groups of components
    • See fig 2.1 (Gamma et al) for sample screen image
  • Want flexibility in many areas
    • structure, algorithms, interface

CS351 - Software Engineering (AY2004)

design issues
Design issues
  • Document structure
    • flexible composition of document components
  • Formatting
    • flexible, configurable formatting policies
  • Embellishing the user interface
    • scroll bars, borders, drop shadows, etc.
  • Multiple look-and-feel standards
    • can’t be hard-wired into the application
  • Multiple windowing systems for portability
  • User operations which are undoable
  • Spell checking and hyphenation
    • won’t be considered

CS351 - Software Engineering (AY2004)

document structure
Document structure
  • A document consists of graphical components such ascharacters, lines, polygons, other shapes
  • The author will view the document as groups of componentsrows, columns, figures, tables, etc.
    • Lexi should allow the author to manipulate these groupsdirectly
  • The internal document structure should support:
    • maintaining the document’s physical structure
    • generating and presenting the document visually
    • mapping positions on the display to documentcomponents (in response to mouse activity)

CS351 - Software Engineering (AY2004)

document structure1
Document structure
  • Proposal is to have a recursive structure for graphicalcomponents

CS351 - Software Engineering (AY2004)

document structure2
Document structure
  • Internal structure corresponding to previous slide will betree-structured:

CS351 - Software Engineering (AY2004)

formatting strategies
Formatting strategies
  • Variety of issues could be addressed
    • e.g. how to break up the components into lines
    • what are the formatting policies?
    • can they be configured on demand?
  • Want to support a variety of strategies independent of thedocument structure

CS351 - Software Engineering (AY2004)

embellishing the user interface
Embellishing the user interface
  • Want to support scroll bars, borders, etc.
  • Want to be able to do this uniformly and flexibly
    • vary these as the user interface evolves
    • even add and remove them on the fly
    • therefore can’t have a fixed inheritance structure
  • Set up a structure for transparent enclosures (like a filter)
    • each enclosure has one component
    • drawing interface is the same as for the component
    • clients don’t know if they are dealing with thecomponent or the enclosure

CS351 - Software Engineering (AY2004)

multiple look and feel standards
Multiple look-and-feel standards
  • Look-and-feel is determined by a family of GUI components
    • buttons, scroll bars, pop-up menus, etc.
    • called widgets
  • Need to be able to generate consistent sets of widgets
    • suit a variety of styles, e.g. Motif, Windows, MacOS, …

CS351 - Software Engineering (AY2004)

multiple windowing systems
Multiple windowing systems
  • Want to support multiple window systems for portability
    • these vary in the level of functionality
    • should we define an abstract windowing system andthen inherit it and override it to satisfy specific cases?
    • support the minimum functionality? maximum?
  • Simpler to define a windowing system that suits our needs
    • allow this to have a variety of implementations
    • each implementation decides how to implement therequired operations

CS351 - Software Engineering (AY2004)

undoable operations
Undoable operations
  • User can request operations from different contexts
    • menu selection
    • mouse operation
    • palette
  • Request need to encapsulate relevant state information sothat they can be undone

CS351 - Software Engineering (AY2004)

gui frameworks
GUI frameworks
  • Even with object orientation, developing a GUI is hard work
    • learning curves of 18 months used to be quoted
    • Java APIs make it a lot easier
  • Significant breakthrough came with GUI frameworks
    • “A framework is a set of cooperating classes that makeup a reusable design for a specific class of software”
    • It is a skeleton application which can be refined byinheritance
    • There are frameworks for GUIs, compiler construction,financial modelling

CS351 - Software Engineering (AY2004)

gui frameworks1
GUI frameworks
  • A GUI framework will include:
    • generic application which will include the central eventloop
    • central event loop will distribute events to relevantgraphical components
    • generic documents = file with contents displayed in awindow
    • generic windows with title bar, close box, resize control,scroll bar
    • generic dialog windows with the ability to display checkboxes, radio controls, buttons, etc.
    • configurable menu manipulation

CS351 - Software Engineering (AY2004)

generic application
Generic application
  • The Generic Application is typically encoded in a classcalled Application
    • this class is subclassed for a specific application
  • The Application class typically:
    • includes the central event loop which is nevermodifiable
    • is instantiated once for a given run of the application
    • may handle multiple document types
    • has method(s) to generate documents
    • has method(s) to setup and respond to appropriatemenus

CS351 - Software Engineering (AY2004)

generic document
Generic document
  • The Generic Document is typically encoded in a class calledDocument
    • this class is subclassed for different specific documents
  • The Document class typically:
    • is instantiated once per document to be processed
    • has methods for fetching and storing the document as afile
    • has method(s) to display the document contents
    • has method(s) to setup and respond to appropriatemenus

CS351 - Software Engineering (AY2004)

generic view
Generic view
  • The Generic View is typically encoded in a class called View
    • this class is subclassed for different specific graphicalcomponents
  • The View class typically:
    • corresponds to an arbitrarily large drawing surface
    • contains functionality to render and print the component
    • contains functionality to maintain the current selection
    • supports various possible representations of the samedata, e.g. spreadsheet, graph, etc.
    • has method(s) to respond to mouse events

CS351 - Software Engineering (AY2004)

generic window
Generic window
  • The Generic Window is typically encoded in a class calledWindow
    • this class is subclassed for different operating systems
  • The Window class typically:
    • implements window-related methods like moving,resizing, closing
    • contains methods to optimise screen updating
    • may contain components to clip the display
  • Note that a View is a logical entity which is displayed in thephysical entity of a Window

CS351 - Software Engineering (AY2004)

generic classes and relationships
Generic classes and relationships
  • Application has multiple documents
  • Document has multiple views
  • View is displayed in a physical region
  • Window contains multiple regions

CS351 - Software Engineering (AY2004)