Design Patterns II Using UML Patterns and Java ObjectOriented Software Engineering Recall Why reusable Designs A design enables flexibility to change reusability minimizes the introduction of new problems when fixing old ones maintainability ID: 583399
Download Presentation The PPT/PDF document "Chapter 8, Object Design:" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Chapter 8, Object Design:
Design Patterns II
Using UML, Patterns, and Java
Object-Oriented Software EngineeringSlide2
Recall: Why reusable Designs?A design……enables flexibility to change (reusability)
…minimizes the introduction of new problems when fixing old ones (maintainability)…allows the delivery of more functionality after an initial delivery (extensibility)…encapsulates software engineering knowledge.Slide3
How can we describe Software Engineering Knowledge?Software Engineering Knowledge is not only a set of algorithmsIt also contains a catalog of
patterns describing generic solutions for recurring problemsNot described in a programming language. Description usually in natural language. A pattern is presented in form of a schema consisting of sections of text and pictures (Drawings, UML diagrams, etc.)Slide4
Algorithm vs PatternAlgorithm:A method for solving a problem using a finite sequence of well-defined instructions for solving a problem
Starting from an initial state, the algorithm proceeds through a series of successive states, eventually terminating in a final state Pattern:„A pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem in such a way that you can use this solution a million times over, without ever doing it the same way twice“ Christopher Alexander, A Pattern language.Slide5
Pattern DefinitionOriginal definition (Christopher Alexander): A pattern is a three-part rule, which expresses a relation between a certain context, a problem, and a solution for conflicting forces (design tradeoffs)
Examples: The conflicting forces between a sunny room and a room that does not overheat on on a sunny sommer afternoonThe conflicting forces between a portable and an efficient software system.Slide6
Pattern Language and Pattern CatalogsPattern Language: A collection of patterns that forms a vocabulary for understanding and communicating ideas
A collection of patterns and the rules to combine them into an architectural style. Pattern languages describe software frameworks or families of related systems.Pattern Catalog:A pattern catalog is a collection of related patterns. It typically subdivides the patterns into at least a small number of broad categories and may include some amount of cross referencing between patterns.Slide7
Schemata for Describing PatternsAlexander’s Schema (“Alexandrian Form”)
A Pattern Language – Towns Buildings Construction, Christopher Alexander, Sara Ishikawa, Murray Silverstein, Vol. 2, Oxford University Press, New York, 1977Gang of Four Schema
Design Patterns: Elements of Reusable Object-Oriented Software
by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Addison Wesley, October 1994 Gang of Five Schema Pattern-Oriented Software Architecture - A System of Patterns, Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal, Wiley and Sons Ltd., 1996.Slide8
Patterns originated in ArchitectureChristopher Alexander’s Philosophy:Buildings have been built for thousands of years by users who where not architectsUsers know more about what they need from buildings and towns than an architect
Good buildings are based on a set of design principles that can be described with a pattern language
Christopher Alexander
* 1936 Vienna, Austria More 200 building projects- Creator of the „Pattern language" - Professor emeritus at UCB.
Although Alexanders patterns are about architecture and
urban planning, they are applicable to many
other disciplines, including software development. Slide9
Alexander’s Schema (“Alexandrian Form”)Name of the PatternPicture of an example for the patternContextProblem: Short description and elaborate description
Solution: Description and DiagramConclusionSections don‘t have explicit headings, sections are separated by symbols 3 diamonds between context and problem and after the solution3 diamonds between solution and conclusionKeyword “Therefore” to separate the problem from the solution.Slide10
Example of a Pattern (Alexander’s Schema)
Source
http://www.patternlanguage.com/leveltwo/patterns.htm
(Subscription required)Slide11Slide12
Name of the Pattern
Picture of an example for the pattern
Problem
Separation of Problem from Solution
Solution: Description
Solution: DiagramSlide13
Context
Separation between Solution and ContextSlide14
More ContextSlide15Slide16
Conclusion 151 Small Meeting RoomsSlide17
Design PatternsDesign Patterns are the foundation for all SE patternsBased on Christopher Alexander‘s patternsBook by John Vlissedes, Erich Gamma, Ralph Johnson and Richard Helm, also called the Gang of Four
Idea for the book at a BOF "Towards an Architecture Handbook“ (Bruce Anderson at OOPSLA’90)
John Vlissedes
* 1961-2005
Stanford
IBM Watson Research Center
Erich Gamma
* 1961
ETH
Taligent, IBM
JUnit, Eclipse,
Jazz
Ralph Johnson
* 1955
University of Illinois,
Smalltalk, Design Patterns, Frameworks, OOPSLA veteran
Richard Helm
University of Melbourne
IBM Research, Boston Consulting Group (Australia)
Design PatternsSlide18
3 Types of Design Patterns (GoF Patterns)Structural PatternsReduce coupling between two or more classes
Introduce an abstract class to enable future extensionsEncapsulate complex structuresBehavioral PatternsAllow a choice between algorithms and the assignment of responsibilies to objects (“Who does what?”)Characterize complex control flows that are difficult to follow at runtimeCreational Patterns
Allow to abstract from complex instantiation processes
Make the system independent from the way its objects are created, composed and represented.Slide19
Taxonomy of Design Patterns (23 Patterns)Slide20
Many design patterns use a combination of inheritance and delegationSlide21
Adapter Pattern
ClientInterface
Request()
LegacyClass
ExistingRequest()
adaptee
Adapter
Request()
Client
Delegation.
Inheritance
The adapter pattern uses inheritance as well as delegation:
- Interface inheritance: Adapter inherits Request() from ClientInterface
- Delegation: Binds LegacyClass to the Adapter.Slide22
Adapter PatternThe adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces“Convert the interface of a class into another interface expected by a client class.”
Used to provide a new interface to existing legacy components (Interface engineering, reengineering).Two adapter patterns:Class adapter: Uses multiple inheritance to adapt one interface to anotherObject adapter: Uses single inheritance and delegation
Object adapters are much more frequent.
We cover only object adapters (and call them adapters).Slide23
Taxonomy of Design PatternsSlide24
Bridge Pattern
Taxonomy in
Application Domain
Inheritance
Inheritance
Delegation
Taxonomy in
Solution DomainSlide25
Why the Name Bridge Pattern?
It provides a bridge between the Abstraction (in the application domain) and the Implementor (in the solution domain)
Taxonomy in
Application Domain
Taxonomy in
Solution DomainSlide26
Using a Bridge The bridge pattern can be used to provide multiple implementations under the same interfaceExample: Interface to a component that is incomplete, not yet known or unavailable during testing
GetPosition() is needed by VIP, but the class Seat is only available by two simulations (AIMSeat and SARTSeat). To switch between these, the bridge pattern can be used:
VIP
Seat
SeatImplementation
SARTSeat
AIMSeat
imp
GetPosition()
SetPosition()Slide27
Seat Implementationpublic interface SeatImplementation {
public int GetPosition(); public void SetPosition(int newPosition);}public class AimSeat implements SeatImplementation {
public int GetPosition() {
// actual call to the AIM simulation system } ….}public class SARTSeat implements SeatImplementation { public int GetPosition() { // actual call to the SART seat simulator } ...}Slide28
Another use of the Bridge Pattern:Supporting multiple Database Vendors
LeagueStoreImplementor
LeagueStore
imp
XML Store
Implementor
ODBC Store
Implementor
JDBC Store
Implementor
ArenaSlide29
Use of the Bridge Pattern:Supporting multiple Database Vendors
LeagueStoreImplementor
LeagueStore
imp
XML Store
Implementor
ODBC Store
Implementor
JDBC Store
Implementor
ArenaSlide30
The Bridge Pattern allows to postpone Design Decisions to the startup time of a systemMany design decisions are made at design time (“design window”), or at the latest, at compile timeBind
a client to one of many implementation classes of an interfaceThe bridge pattern is useful to delay this binding between client and interface implementation until run timeUsually the binding occurs at the start up of the system (e.g. in the constructor of the interface class).Slide31
Adapter vs BridgeSimilarities:Both hide the details of the underlying implementation
Difference:The adapter pattern is geared towards making unrelated components work togetherApplied to systems that are already designed (reengineering, interface engineering projects) “Inheritance followed by delegation”A bridge, on the other hand, is used up-front in a design to let abstractions and implementations vary independently
Green field engineering of an “extensible system” New “beasts” can be added to the “zoo” (“application and solution domain zoo”, even if these are not known at analysis or system design time
“Delegation followed by inheritance”.Slide32
Taxonomy of Design Patterns (23 Patterns)Slide33
Facade PatternProvides a unified interface to a set of classes in a subsystemA façade consists of a set of public operations
Each public operation is delegated to one or more operations in the classes behind the facadeA facade defines a higher-level interface that makes the subsystem easier to use (i.e. it abstracts out the gory details).Slide34
Subsystem Design with Façade, Adapter, BridgeThe ideal structure of a subsystem consists of an interface object
a set of application domain objects (entity objects) modeling real entities or existing systemsSome of these application domain objects are interfaces to existing systemsone or more control objectsWe can use design patterns to realize this subsystem structureRealization of the interface object:
Facade
Provides the interface to the subsystemInterface to the entity objects: Adapter or BridgeProvides the interface to an existing system (legacy system)The existing system is not necessarily object-oriented! Slide35
Good Design with Façade, Adapter and Bridge A façade
should be offered by all subsystems in a software system which provide a set of services The façade delegates requests to the appropriate components within the subsystem. The façade usually does not have to be changed, when the components are changedThe adapter pattern should be used to interface to existing components and legacy systems
Example: A smart card software system should use an adapter for a smart card reader from a specific manufacturer
The bridge pattern should be used to interface to a set of objects with a large probability of changeWhen the full set of objects is not completely known at analysis or design time (-> Mock Object Pattern)When there is a chance that a subsystem or component must be replaced later after the system has been deployed and client programs use it in the field.Slide36
Design ExampleSubsystem 1 VIP can call on any component or class operation look in Subsystem 2 (Vehicle Subsystem).
Vehicle Subsystem
VIP
AIM
Card
SART
SeatSlide37
Realizing an Opaque Architecture with a Facade The Vehicle Subsystem decides exactly how it is accessed No need to worry about misuse by callers
A subsystem with a façade can be used in an early integration test We need to write only stubs for each of the public methods in the façade.
VIP Subsystem
AIM
Card
SA/RT
Seat
Vehicle Subsystem FacadeSlide38
Taxonomy of Design PatternSlide39
Strategy PatternDifferent algorithms exists for a specific taskWe can switch between the algorithms at run timeExamples of tasks:
Different collision strategies for objects in video gamesParsing a set of tokens into an abstract syntax tree (Bottom up, top down)Sorting a list of customers (Bubble sort, mergesort, quicksort)Different algorithms will be appropriate at different timesFirst build, testing the system, delivering the final productIf we need a new algorithm, we can add it without disturbing the application or the other algorithms.Slide40
Strategy Pattern
Context
ContextInterface()
Strategy
AlgorithmInterface
*
ConcreteStrategyC
AlgorithmInterface()
ConcreteStrategyB
AlgorithmInterface()
ConcreteStrategyA
AlgorithmInterface()
Policy decides which ConcreteStrategy is best in the current Context.
PolicySlide41
Using a Strategy Pattern to Decide between Algorithms at Runtime
Database
SelectSortAlgorithm()
Sort()
*
SortInterface
Sort()
BubbleSort
Sort()
QuickSort
Sort()
MergeSort
Sort()
Policy
DevelopmentTimeIsImportant
ExecutionTimeIsImportant
SpaceIsImportant
ClientSlide42
Supporting Multiple implementations of a Network Interface
NetworkInterface
open()
close()
send()
receive()
NetworkConnection
send()
receive()
setNetworkInterface()
Application
Ethernet
open()
close()
send()
receive()
WaveLAN
open()
close()
send()
receive()
UMTS
open()
close()
send()
receive()
LocationManager
Context =
{Mobile, Home, Office}Slide43
Taxonomy of Design PatternsSlide44
Abstract Factory Pattern Motivation Consider a user interface toolkit that supports multiple looks and feel standards for different operating systems:How can you write a single user interface and make it portable across the different look and feel standards for these window managers?
Consider a facility management system for an intelligent house that supports different control systems:How can you write a single control system that is independent from the manufacturer?Slide45
Abstract Factory
Initiation Assocation:
Class
ConcreteFactory2 initiates theassociated classes ProductB2 and ProductA2
AbstractProductA
ProductA1
ProductA2
AbstractProductB
ProductB1
ProductB2
AbstractFactory
CreateProductA
CreateProductB
Client
CreateProductA
CreateProductB
ConcreteFactory1
CreateProductA
CreateProductB
ConcreteFactory2Slide46
Applicability for Abstract Factory PatternIndependence from Initialization or RepresentationManufacturer IndependenceConstraints on related productsCope with upcoming changeSlide47
Example: A Facility Management System for a House
LightBulb
EIBBulb
LuxmateBulb
Blind
EIBBlind
LuxmateBlind
IntelligentHouse
HouseFactory
createBulb()
createBlind()
LuxmateFactory
EIBFactory
createBulb()
createBlind()
createBulb()
createBlind()Slide48
Clues in Nonfunctional Requirements for the Use of Design PatternsText: “manufacturer independent”, “device independent”,
“must support a family of products”=> Abstract Factory PatternText: “must interface with an existing object”=> Adapter Pattern
Text: “must interface to several systems, some
of them to be developed in the future”, “ an early prototype must be demonstrated”=>Bridge PatternText: “must interface to existing set of objects”=> Façade PatternSlide49
Clues in Nonfunctional Requirements for use of Design Patterns (2)Text: “complex structure”,
“must have variable depth and width” => Composite PatternText: “must provide a policy independent from the mechanism”Strategy PatternText:
“must be location transparent”
=> Proxy PatternText: “must be extensible”, “must be scalable” => Observer Pattern (MVC Architectural Pattern)Slide50
SummaryComposite, Adapter, Bridge, Façade, Proxy (Structural Patterns)Focus: Composing objects to form larger structures
Realize new functionality from old functionality, Provide flexibility and extensibilityCommand, Observer, Strategy, Template (Behavioral Patterns)Focus: Algorithms and assignment of responsibilities to objectsAvoid tight coupling to a particular solutionAbstract Factory, Builder (Creational Patterns)
Focus: Creation of complex objects
Hide how complex objects are created and put togetherSlide51
ConclusionDesign patterns provide solutions to common problemslead to extensible models and code
can be used as is or as examples of interface inheritance and delegationapply the same principles to structure and to behaviorDesign patterns solve a lot of your software development problemsPattern-oriented developmentSlide52
Additional Design HeuristicsNever use implementation inheritance, always use interface inheritanceA subclass should never hide operations implemented in a superclass
If you are tempted to use implementation inheritance, use delegation insteadSlide53
Example: Modeling Electrical Outlets and PlugsThe Type F electrical plug is identified by two round pins spaced 19mm apartA Type F outlet has two earth (ground) clips on its side, rather than a female earth contact.
The type F electric frequency is in Hertz (Hz, cycles per second). Even if voltages are similar, a 60 Hz device may not function properly on a 50 Hz current, so check if the type F wall plug is compatible with your electronics. Otherwise, one needs a type F plug adaptor that can lower the internal current. Type F adapters cannot, however, change the number of cycles.Slide54
Plugs, Transformers and AdaptersAn electric plug has a prong which can be inserted into the receptable of an electrical outlet
A power transformer allows an appliance to get a specific voltage (110 V) from an electrical outlet providing another voltage (220 V) A plug adapter connects appliances and electrical outlets that are incompatible with each other. One end of the adapter is attached to the plug used by the appliance, while the other end of the adapter is connected with the electrical outletProvide a UML model for a plug adapter that converts an appliance using a type F electrical plug (Germany) with a Type A electrical outlet (USA).A power adapter is an electrical system consisting of a plug adapter and a power transformer
Model a power adapter that connects a computer notebook (of your choice) outlet with a Type F (Germany) electrical outlet as well as Type A electrical outlet (USA).Slide55
Plugs, Transformers and AdaptersAn electric
plug has a prong which can be inserted into the receptable of an electrical outletA
power transformer allows an
appliance to get a specific voltage (110 V) from an electrical outlet providing another voltage (220 V) A plug adapter connects appliances and electrical outlets that are incompatible with each other. One end of the adapter is attached to the plug used by the appliance, while the other end of the adapter is connected with the electrical outletProvide a UML model for a plug adapter that converts an appliance using a type F electrical plug (Germany) with a Type A electrical outlet (USA).A power adapter is an electrical system consisting of a plug adapter and a power transformerModel a power adapter that connects a computer notebook (of your choice) outlet with a Type F (Germany) electrical outlet as well as Type A electrical outlet (USA).Slide56
Universal AdaptersA universal adapter offers all the prongs available in the world and can be inserted into all the electrical outlets anywhere in the worldModel a universal adapter that can be inserted into outlets with 2 thin, 3 thin, 2 thick or 3 thick hole receptables and that provides 2 thin, 3 thin, 2 thick and 3 thick prongs
Many 220 V countries have converted to the EU standard of 230 V. Legacy 220 V appliances tolerate small variations above or below the rated voltage. But severe current variations can damage these appliancesHow do you model severe current variations? How do you prevent them?Model both, the power transformer as well as the universal power adapter, in a single system model. You can choose UML or SysML as modeling language. Which one is better for the modeling task? Justify your answer. Slide57
Example of an Algorithm: Solving the Rubic CubeSpeed: Rubik’s Cube in 6 seconds http://www.youtube.com/watch?v=jI_zjWssn2g&feature=related
Concurrency: 2 Rubik Cubes at the same time http://www.youtube.com/watch?v=RW3akfdEGI8&feature=relatedScalability: 3 Rubik Cubes in a rowhttp://www.youtube.com/watch?v=api7yyAoAug&feature=channel
Scalability: 10 Rubik Cubes in a row
http://www.youtube.com/watch?v=51z0Tf76f3Y&feature=channelMiscellaneous categories: Rubik cube by a 3 year old http://www.youtube.com/watch?v=uNcf7KD3QUg&feature=relatedRubik Cube blindfolded http://www.youtube.com/watch?v=JCkI2qh1SF4&NR=1Rubik Cube by a Robothttp://www.youtube.com/watch?v=bNAnUygqOYc&feature=channel