Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Design Patterns with FujabaIntense Course, 5th-9th October 2009
Ruben [email protected]
Kassel University
Department of Software EngineeringWilhelmshöher Allee 73
34121 KasselGermany
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 2
Timetable
Monday, October 5th:10.15-11.45, room 40512.00-13.30, room 40314.15-15.45, room 405 (Exercise)
Tuesday, October 6th:10.15-11.45, room 40412.00-13.30, room 40414.15-15.45, room 405 (Exercise)
Friday, October 9th:10.15-11.45 room 40212.00-13.30 room 31514.15-15.45 room 315 (Exercise)
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 3
What we have learned yesterday
General Design Principles & Design Patterns Introduction
Modeling with Fujaba4Eclipse
More Design Patterns... with live coding Strategy Pattern
Fujaba4Eclipse: Modelling Methods Simple Control Flow, Statement Activities Creating and Deleting Objects
More Design Patters: Composite Pattern (with Fujaba4Eclipse) Visitor Pattern (in Java)
Exercise 1: Strategy Pattern
Homework 1: Implement Composite and Visitor Pattern in Java or Fujaba4Eclipse
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 4
Overview
More Design Patterns... #4-8: DP #4: Visitor Pattern DP #5: Adapter Pattern DP #6: Strategy and Hook Pattern DP #7: Chain of Responsibility DP #8: State Pattern
Fujaba4Eclipse Story Driven Modelling continued...
More Design Patterns... #9-11: Template Method Pattern Decorator Pattern Observer Pattern (Listener)
Fujaba4Eclipse: PropertyChange-Mechanism
Exercise 2, Homework 2
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 5
Exercise 1
Implement the single Alarm / delegation example from day1/slide16 in Java: Use the singleton pattern for the class House
Write a method, which instanciates all types of alarms, adds them individuallyto the house and calls house.alarm() each time (Strategy Pattern)
Model the same example in Fujaba4Eclipse (hint: use a different packagename)
Change your main()-Method to use the generated code (or model one)
Use the eDOBS to visualize your object structure! Can you observe any differences between plain java and generated classes?
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 6
Live modeling
of Exercise 1
House
run ()alarm ()
FlashLightalarm()
Sirenalarm()
MailAlarmalarm()
alarmDevice AlarmDevicealarm ()
cardinality here? 1 ? n ?we start with 1 ...
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 7
Homework 1:
Implement Abstract-, RegularFile and Directory using the CompositePattern as shown before (either in plain java or as Fujaba4Eclipsemodel, assume unix-style filesystem, you might omit Root/Drive)
Delegate RegularFile(String name), child computation, getName() andgetFileSize() to java.io.File in the class RegularFile
Implement findAll() and countFiles() like shown in the lecture / session3! How many files are there?
Implement findAll(String extension) - should list only files with the givenfile extension. How can this be combined with countFiles()? Find asolution that prints just the number of .java-Files!
Count the files in the current directory by calling traverse(new RegularFile(“.“), visitor); using theCountFilesVisitor. How many are there?
Write a SummarizeFileSizesVisitor ! What is the summarized size of the files in the current directory? Advanced: Add a file extension filter to the CountFilesVisitor. How many *.java-Files are there?
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 8
Visitor motivation
Now we want to implement some operations: Count all files recursively Summarize the file size of all files ... Find empty directories ... Difficult with the current approach!!!
Decouple tree traveral from operation (e.g.System.out.print)
Allow different operations, group then in classes
Operations might be interested only in a certain type of thetraveral elements
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 9
Implementing
Visitor Pattern
Live
(CountFilesVisitor and
FindEmptyDirectoriesVisitor)
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 10
DP #4: Visitor Pattern - Specification
Pass a Visitor to all Elements while iterating/traversal
Elements call corresponding visit()-Method
Consequences: Benefits and Drawbacks Separation of concern Adding new ConcreteElement is hard, operations not Encapsulation? Known Usages: Parser, e.g. javacc
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 11
Adapter Pattern - example and motivation
Run dpexamples.day2.adap.SimpleTreeViewer Shows a graphical hierachical tree of data
We want to adapt to java.io.File now, to present thedirectory tree Which is a hierarchical tree as well!
Problem: Swing expects TreeNode with its operations butjava.io.File provides differrent methods!
Solution: Adapter, which satisfies (implements) the treeinterface but delegates to java.io.File!
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 12
Live implementation
of the Adapter Pattern
TreeViewer -> java.io.File(might be helpful for homework 1)
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 13
Adapter Pattern: Specification
Adapt between Target and Adaptee
Either use inheritance or delegation
Known Uses: Heavily in the Eclipse Framework
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 14
Hook Pattern
Additional functionality can be added at runtime
Delegation to many Handlers, might be ordered
(See HouseAlarm Example of Exercise 1)
Example:
House
run ()alarm ()
FlashLightalarm()
Sirenalarm()
MailAlarmalarm()
alarmDevice AlarmDevicealarm ()n<< ordered >>
public void alarm(){ ...for (a : alarmDevices){alarm.alarm();
} ...
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 15
Hook Pattern : Specification
Delegate Request to many objects
Only (abstract) supertype known to Client
Example: Java Servlets (multiple instances), Eclipseplugins...
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 16
Chain of Responsibility
Based on Hook: Handlers as well But handlers itself might be linked
Stop when one Handler received the request Might use return value
Example:House
run ()alarm ()
FlashLightalarm()
Sirenalarm()
MailAlarmalarm()
alarmDevice AlarmDevicealarm ()1
< next1:1
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 17
Live implementation
of CoR
in Fujaba4Eclipse / HouseAlarm
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 18
Modeling Methods with Fujaba4Eclipse
=>
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 19
Story / Activity Diagrams
Start -> Control Flow -> Stop Transitions in between
Statement Activity for plain Java Code
Story Pattern (aka Activity) contain Object diagrams Specify a Graph Transformation
Black: match Green: create Red: destroy
Objects might have modifiers: Create, Destroy „bound“ Objects omit the Type
Links between objects Same modifiers - create (implicit), destroy
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 20
Advanced Modelling
Success- and Failure-Transition
Each-time-Activity for iterations Doubleclick or Edit Story Activity Might use each-time- and end-for-all-Transition
Collaboration statements Number for Timeflow, enter method
Constraints
You can verify whether the method does what you expectby looking at the generated source code (at first)!
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 21
State Pattern
Based on Strategy Pattern - again to-one association Eliminate if/elseif/else-chains
But Strategy gets changed systematically: Each State is a different instance States collaborate
Example: HouseAlarm Each alarm should be used only three times, then it
should change to the next alarm automatically
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 22
Live implementation
of State Pattern
in plain Java / HouseAlarm
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 23
State Pattern: Specification
Specification: same as Strategy... State change left to implementation
Known Uses: Various StateChart-Implementations, e.g. in Fujaba Many extensions like hierarchy, transitions, events...
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 24
SDM / Activity-Diagrams (recapitulation)
Activities and Transitions
Start with Class- and Method-Name
Activities for working steps
Transitions (with Guards like success,failure...) for control flow
Stop, Diamond...
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 25
SDM Activity Diagrams Ref.: Control Flow
Activities
start activity
stop activities
rule acitivities
code activities
branch activities
Transitions without Guard [success] and [failure] [[each time]] and [[end]] [boolean condition] [else] [exception]
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 26
SDM Activity Diagrams: Control Flow (2)
Activities
start activity
stop activities
rule acitivities
code activities
branch activities (diamond)
Transitions without Guard [success] and [failure] [[each time]] and [[end]] [boolean condition] [else] [exception]
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 27
Advanced SDM
Constraints
Collaboration Statements Ordered Might declare, loop, iterate...
Object constraints: Negative Objects: a object that must not be there Optional Objects: a object that might be there (for a operation)
Links: first, last, index, key...
Virtual Paths
Alternatives modeling iterations Foreach vs. Success/Failure-Transitions
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 28
SDM - Execution Engine Enter a Activity...
Search and match Objects Take over all bound objects from previous steps or parameters Follow links... Evaluate attribute assertions Bind matched objects to local variables
Evaluate Constraints On Error: Do nothing more, follow Failure-Transition
Create Objects, Links
Assign Attributes
Invoke Collaboration Statements Set local Variables
Delete Objects, Links
next Transition...
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 30
Template Method Pattern (aka Single-Hook)
Motivation Algorithms with a fixed outer structure But individual steps might vary
Example ImageConverter:
Collect all Files in a Directory... then, on each idividual file: Open, read, adjust brightness/contrast Transform (rotate by 90degrees if needed Compress and write
Here: AlarmDevice.alarm() splits into start and stop
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 31
Live implementation
of the
Template Pattern
in plain java using
AlarmDevice start()/stop()
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 32
Template Method Pattern : Specification
Outer, general algorithm
Specialized steps
Consequences: Benefits and drawbacks Helps to have a defined structure No object-level composition
Known Uses: probably any abstract class :)
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 33
Decorator Pattern
Template Method doesn‘t help if we need to mix things Combine different open, transform and write operations Compose different transforms at runtime, each one encapsulated in
one class (GeneralFileConverter)
A deeper look into the transform() of the ImageConverter Remove red-eyes-effect Adjust Brightness/Contrast Rotate by 90degrees
Idea behind the Decorator: Keep the interface ( transform() ) But delegate to individual objects
The Java API contains a good example: Streams
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 34
Showing the decorator live
with java.io.*Stream
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 35
Decorator Pattern : Specification
Delegate to objects
Based to Strategy (delegation chain of length 1)
Consequences: Runtime flexibility Lots of Objects
Known Uses: java.io.*Stream, -Reader and -Writersubclasses
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 36
Observer Pattern
Basic Pattern behind MVC
To-many relationship between subject and observers
aka Publish-Subscribe-Protocol
Example: One Sensor in the House notifies all AlarmDevices
House
run ()alarm ()
FlashLightalarm()
Sirenalarm()
MailAlarmalarm()
alarmDevice AlarmDevicealarm ()
Sensornotify()
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 37
Live implementation
of the Observer Pattern
with HouseAlarm
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 38
Observer Pattern : Specification
Observers register at the Subject
Subjects changes are delivered to all Observers
Updates: Push- vs. Pull
Known Uses: GUI/Widget Libraries, e.g. various Listeners in Swing
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 39
PropertyChange Mechanism
General JDK mechanism (some default implementation ismissing), basically the Observer Pattern
Slighty different Terminology: Listener, Source, Property
adopted in the Fujaba Code Generator Uses Constants in the generated Code Robust
Requires <<JavaBean>> stereotype in each class whichshould fire events
All setters fire accordingly... oldValue, newValue
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 40
Lets have a look...
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 41
Exercise 2
Start with your exercise from yesterday or download andextract workspace.dp2.zip .
Extend the HouseAlarm model in Class Diagram „Day2:HouseAlarm as Hook / CoR“ with the (modified) Chain-of-Reponsibility-Pattern Choose either CoR-with-ordered-to-n-assoc (easier,
Slide n) or CoR-with-next-link (Slide n2) delegate alarm() to the first active AlarmDevice
What could your program do if no AlarmDevice isresponsible? Implement a solution that ensures that thealarm() won‘t get lost
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 42
Implementation of Exercise 2:
Chain of Responsibility
with HouseAlarm
Fujaba Modeling & Design Patterns © 2009 Ruben Jubeh, Albert Zündorf, University of Kassel 43
Homework 2
Start with the Class Diagram „Homework2a: Filesystem“: Model the Visitorpattern! That means: Add a traverse-method to FileSystem (Use a foreach-activity. Might use
recursion) Add an abstract Visitor interface Let the concrete classes accept the visitor during traversal and let them
call the visitor finally Optional: implement a ListAllFilesVisitor
Start with plain java HouseAlarm (Homework/src/dpexamples.homework2b) Let MailAlarm.alarm() throw a new RuntimeException(“Mail server down!“).
Implement the state pattern by adding some logic which switches to theSiren then. Where should the try/catch be? Where is the strategyexchange?