G - PowerPoint PPT Presentation

1 / 267
About This Presentation
Title:

G

Description:

Quantitative project management: ... Agile Development Processes XProgramming Agile ... JUnit 4.0 in 10 minutes TDD Create a Java project as usual Project ... – PowerPoint PPT presentation

Number of Views:299
Avg rating:3.0/5.0
Slides: 268
Provided by: Petitp5
Category:

less

Transcript and Presenter's Notes

Title: G


1
Génie logicielSoftware EngineeringC.
Petitpierre
2
Thèmes du cours
  • UML (Unified modeling language)
  • Processus de développement
  • Design Patterns
  • Java Server Faces, EJB3
  • JET, use of templates
  • Chargement de databases en XML SAX, FSM,
    JavaCC
  • Langage permettant la validation CCS et
    threads

3
Personnages et sites
  • Martin Fowlerhttp//martinfowler.com/
  • Scott Amblerhttp//www.ambysoft.com/

4
Projet de génie logiciel
  • Gestion des commandes des clients dans un
    restaurant
  • Prendre une commande
  • Lafficher au comptoir et à la cuisine
  • Indiquer quand elle est prête
  • Faire les factures
  • Plan de travail disponible sur le
    Webhttp//ltiwww.epfl.ch/petitp/GenieLogiciel

5
UMLUnified Modeling Language(OMG object
management group)
http//www.uml.org/ http//www.omg.org/
6
UML usage
  • UML is particularly useful to sketch IT
    applications (pencil and eraser or PowerPoint)
  • It can be adapterused to document applications
    (reverse engineering consists of recreating the
    diagrams from the code, which is a cheap way of
    making acheap documentation)
  • It is used by ArcStyler and OptimalJ (among
    others) to create applications(it is difficult
    to enter the application details in these systems)

7
UML / RUP history
  • Rational founded in 1981 around a processor and
    development environments for Ada and C
  • In 1990, Grady Booch develops Rose for Rational,
    a tool to specify models
  • In 1995, Rational hires James Rumbaugh, buys Ivar
    Jacobson company, and the three amigos define
    UML (unified modeling language)
  • Same year, Philippe Kruchten defines RUP
    (Rational unified process)
  • In 2002, IBM buys the company for 2B (beside
    UML, they are consultants for many customers)

8
UML Rules of Thumb(features not bugs !)
  • Nearly everything in UML is optional
  • UML models are rarely complete
  • UML is designed to be open to interpretation
  • UML is intended to be extended
  • UML 2.0 in a nutshell, Dan Pilone, OReilly, 2005

9
UML
  • Use cases
  • Class diagrams
  • Sequence diagrams
  • Collaboration diagrams
  • State diagrams / Activity diagrams

10
UML
Transfer Money
Open Account
ltltincludegtgt
ltltincludegtgt
Check Balance
Withdraw Money
  • Use case diagram for an ATM
  • (automate de banque)
  • Only lists the names of the use case scenarios,
    which describe the various functions defined by
    the application

11
UML Use case (scenario)
  1. A client inserts a card into the ATM.
  2. The system reads and validates the card
    information.
  3. The system prompts for a PIN.
  4. The client enters the PIN.
    (client, system actors)
  5. The system validates the PIN
  6. The client selects Withdraw Money
  7. The client enters the requested amount.
  8. The system requests the amount from the clients
    account.
  9. The system asks the client to remove the card.
  10. The system dispenses the requested amount from
    the banknote buffer(only done if the requested
    amount has been granted in 8).

12
UML Use case (extension)
  • A client inserts a card into the ATM.
  • The system reads and validates the card
    information.
  • The system prompts for a PIN.
  • The client enters the PIN.
    (client, system actors)
  • The system validates the PIN
  • Extensions
  • 5a. If the PIN is invalid, the system rejects the
    card
  • The client selects Withdraw Money
  • The client enters the requested amount
  • . . .

13
UML Dictionary
  • If you work in a new domain (bank, assurances,
    production) you will need to create a small
    dictionary

14
Class diagram with visibility
Bill - numberOfItems  int addItem(itemItem)
- getFirstItem()  Item getNextItem()  Item
public visible from everywhere - private local
to the class protected visible only from the
derived class package visible from the package
(Java) (actually this is too far into the details
for a sketch)
15
Class diagram inheritance
16
UML note(Omondo on Eclipse)
17
Class diagram association
Weakest form of relationship (Can be used, for
example, to indicate that a method may call
a method in another class)
18
Class diagram aggregation
Bill - numberOfItems  int addItem(itemItem)
- getFirstItem()  Item getNextItem()  Item
BillItem ProductNumber  int
NumberOfPieces  int UnitPrice  int
1
0..
Customer name  String
Used to show that an object instantiated from
that class contains another object (in an
attribute) or a collection of objects (collection
in an attribute)
19
Class diagram composition
Window
menu
1
1..
Strong relationship. If the main class is
deleted, the subclass has no meaning any more and
is destroyed. Not often used.
20
Sequence diagram
Main
Object X
Object B
new ( )
start ( )
run ( )
xMeth ( )
21
Collaboration diagram (Omondo)
22
Collaboration diagram(context of the application)
temporary dataset
GUI
controller
DB inter-face
remote database proxy
employee
printer_A
printer_B
Non standard use of specific icons
23
State diagram / state charts
application
enter
display
ignore
exit
start
timeout
doing
previous
next
enter
0
2
ignore
display_francs
1
display_euros
24
State diagram / state charts
E
start
timeout
Entry point
A
action
Exit
25
Relation between a state chart and a use case
state chart diagram of a component
component
collaboration diagram with use case 1
collaboration diagram with use case 2
Collaboration diagram actors and
repositories Use case what they do and in what
sequence State chart all actions of a component
26
Activity diagrams
  • Inspired from the Petri nets
  • May fork and join threads
  • The use of forks and joins is not a very good
    idea !! It makes it very difficult to follow the
    state of a program

27
Activity diagram an example
registration
Fork Two threads Join
quit
find
close
log
register
28
ltlt Stereotypes gtgt
Customer name  String
ltlt CMP EJB gtgt Bill - numberOfItems  int
ltlt hasBills gtgt
29
UML a technique to start a development
Identifying classes Borrowing The library
contains books and journals. It may have several
copies of a given book. Some of the books are for
short term loans only. All other books may be
borrowed by any library member for three weeks.
Members of the library can normally borrow up to
six items at a time, but members of staff may
borrow up to twelve items at one time. Only
members of staff may borrow journals. library is
out of scope item is vague short term loan is
an event time is out of scope week is a measure
of time system is not part of the domain We
keep book journal copy (of book) library
member staff member
30
Use of a sequence diagram
Main
Object X
Object B
new ( )
start ( )
Start of the thread (calls method run)
run ( )
foo ( )
xMeth ( )
Method executed at the same time as method run
or method xMeth.
return
The example explains how the Java threads work
31
Corresponding code 1st solution
public class Main static ActiveObject a1
static public void main (String args)
a1 new ActiveObject () // create an active
object a1.start() //
start the active object a1.foo()
class ActiveObject extends Thread public
void foo() public void run ()
for () System.out.println("ActiveO
bject running") try
Thread.sleep(3000) catch (Exception e)

32
Corresponding code 2nd solution
public class Main static AnObject a2
static public void main (String args)
a2 new AnObject () // create an active
object new Thread(a2).start() // start
the active object a2.foo()
class AnObject implements Runnable
public void foo() public void run ()
for () System.out.println("An
Object running") try
Thread.sleep(2000) catch (Exception e)

33
Use of sequence diagrams
Threaded object 2
Threaded object 1
Semaphore
run ( )
run ( )
stop ( )
position of the wait ( ) (blocking)
stop(), kick() are user-defined methods
kick ( )
position of the notify ( ) (non blocking)
Explains how the wait-notify commands work see
code next slide
34
Code corresponding to the sequence diagram
class T2 implements Runnable Sem tm
public T2 (Sem t) tm t public void
run () for ()
tm.kick() Thread.sleep(1000)

class T1 implements Runnable Sem tm
public T1 (Sem t) tm t public
void run () for ()
tm.stop()
class Sem public void kick ()
synchronized (this) notify()
public synchronized void stop ()
try wait() catch
(InterruptedException ie)
There are two different ways of using
synchronized.
35
Creation of the previous threads
sem new Sem() new Thread(new
T1(sem)).start() new Thread(new
T2(sem)).start()
36
Yet another way of using synchronize
class Sem String s // empty string,
or any object public void kick ()
synchronized (s) notify()
public void stop ()
synchronized (s) try
wait() catch
(InterruptedException ie)
Every Java object has provision for thread
synchronization
37
Development Process
38
Well-known development processes
  • RUP (Rational Unified Process)
  • CMMI (Capability Maturity Model Integration)
  • Agile / XP (eXtreme Programming)

39
Waterfall Development Process
Analysis
Design
Implementation
Testing
?
Maintenance
Civil engineering One first draws plans and
only then are they realized ! Why wouldnt it
work with software ?
40
Iterative Process (spiral)
Test
Implementation
Maintenance
Development
Analysis
Design
Superficial analysis, design, implementation and
test of the whole application, then better
analysis, design, implementation and test, and
improvement at each revolution ? or ? Thorough
analysis, design, implementation and test of a
part, and then analysis, design, implementation
and test of a new part at each revolution ?
41
Agile Development Process
Most important characteristics No long term
planning. Deliver working software frequently
(from a couple of weeks to a couple of months,
with a preference to the shorter timescale).
42
RUP
43
RUP Rational Unified Process
  • For the project manager
  • What is important in a project
  • What leads to failures
  • Working team composition
  • Management tools
  • Very little on how to do things !

44
RUP Warning
  • What is Rational's RUP ?
  • It is a methodology. But to sell it, Rational
    supplies a bunch of html pages (about 16000
    pages). There are some documentation templates
    also. A warning though, if you are thinking to
    get into a good methodology in reasonable time,
    then you need to rethink, RUP will take a
    looooooooooong time to grasp, implement and
    finally there is a 50 risk that you will never
    reap the benefits.
  • http//www.theserverside.com

45
RUP
  • Available on a CD-Rom that must be customized.
  • Accompanied by P. ?Kruchten,
  • The Rational Unified Process an Introduction,
  • Characteristics and best practices
  • Iterative process
  • Requirement management
  • Architecture and use of components
  • Modeling and the UML
  • Quality of development process and product
  • Change management (tools)

46
RUP 1 - Iterations
47
RUP2 - Requirement management
  • Requirements are stakeholders needs, goals and
    wishes. (stakeholders - parties prenantes
    contractor, customers, users, employees)
  • (FURPS functionality, usability, reliability,
    performance and supportability)
  • URSP non functional requirements

48
RUP3 - Architecture
  • Components
  • A nontrivial piece of software, a module, a
    package, a subsystem, a layer, major classes
  • CORBA (remote objects), ActiveX, JavaBeans, a Web
    page, database table
  • Mechanisms such as persistency and communication
    tool, patterns (MVC, ORB object request broker .
    . .)

49
RUP4 - UML and modeling
Transfer Money
Open Account
ltltincludegtgt
ltltincludegtgt
Check Balance
Withdraw Money
  • Use case diagram for an ATM
  • (automate de banque)

50
RUP 4 - UML and modeling
  • A scenario or use case
  • (the term use case is more general)
  1. A client inserts a card into the ATM.
  2. The system reads and validates the card
    information.
  3. The system prompts for a PIN.
  4. The client enters the PIN.
    client, system actors
  5. The system validates the PIN
  6. The client selects Withdraw Money
  7. The client enters the requested amount.
  8. The system requests the amount from the clients
    account.
  9. The system asks the client to remove the card.
  10. The system dispenses the requested amount from
    the banknote buffer(only done if the requested
    amount has been granted in 8).

51
RUP 4 - Collaboration diagram
P. Kruchten, The Rational Unified Process An
Introduction, Addison-Wesley
52
RUP 5 - Quality
  • Quality
  • Reliability (no bug)
  • Functionality (does what it is meant for)
  • Performance
  • Tests
  • Unit tests
  • Integration tests (interactions of units)
  • System test (complete application)
  • Acceptance test (same, but performed by the
    buyer)
  • Regression tests (repetition of previous tests to
    assure that the new features have not introduced
    bugs in the former part)

53
RUP 6 - Change management
  • ClearQuest
  • Tool for change request management
  • ClearCase
  • Tool for configuration management

54
CMMI
55
CMM - CMMI
  • Capability Maturity Model(developed by the
    Software Engineering Institute of CMU)
  • Capability Maturity Model Integration(upgrade of
    CMM)
  • http//ltiwww.epfl.ch/petitp/GenieLogiciel/CToMFe
    b02.pdf(article by a RUP vendor, excerpts on
    the next slides)

56
CMMI
  • Level 1 (initial)
  • Represents a process maturity characterized by
    unpredictable results.
  • Ad hoc approaches, methods, notations, tools,
    and reactive management translate into a process
    dependent predominantly on the skills of the team
    to succeed.

57
CMMI
  • Level 2 (managed)
  • Represents a process maturity characterized by
    repeatable project performance.
  • The organization uses foundation disciplines for
    requirements management project planning
    project monitoring and control supplier
    agreement management product and process quality
    assurance configuration management and
    measurement/analysis.
  • For Level 2, the key process focus is on
    project-level activities and practices.

58
CMMI
  • Level 3 (defined)
  • Represents a process maturity characterized by
    improving project performance within an
    organization. Consistent, cross-project
    disciplines for Level 2 kpas (key process areas)
    are emphasized to establish organization-level
    activities and practices.
  • Additional organizational process areas include
  • Requirements development, technical solution,
    product integration, verification, validation,
    risk management, organizational training,
    organizational process focus, decision analysis
    and resolution, organizational process
    definition, integrated project management

59
What are risks ?
If your customers need a new system by a specific
date the risk is high. If that system is a new
challenge for your software group the risk is
even greater. If that system is a new challenge
to the entire software industry the risk is still
greater even. Unsatisfied employees also
participate in the risk.
60
CMMI
  • Level 4 (quantitatively managed)
  • Represents a process maturity characterized by
    improving organizational performance.
  • Historical results for Level 3 projects can be
    exploited to make trade offs, with predictable
    results, among competing dimensions of business
    performance (cost, quality, timeliness).
  • Additional Level 4 process areas include
  • Organizational process performance setting norms
    and benchmarks for process performance.
  • Quantitative project management executing
    projects based on statistical quality-control
    methods.

61
CMMI
  • Level 5 (optimized)
  • Represents a process maturity characterized by
    rapidly reconfigurable organizational performance
    as well as quantitative, continuous process
    improvement.
  • Additional Level 5 process areas include
  • Causal analysis and resolution proactive fault
    avoidance and best practice reinforcement.
  • Organizational innovation and deployment
    establishing a learning organization that
    organically adapts and improves.
  • (few companies arrive at that level)

62
Agile Development Processes
  • XProgramming

63
Agile Development Process
http//agilemanifesto.org http//martinfowler.com
http//www.ambysoft.com/
Most important characteristics No long term
planning. Deliver working software frequently,
from a couple of weeks to a couple of months,
with a preference to the shorter timescale.
64
XProgramming
  • Complaint and excuse of the programmer
  • the problem with this project is that the
    requirements are always changing
  • Actually it is always and will always be the
    case, we must thus do with it !
  • ? XProgramming
  • (http//www.extremeprogramming.org)

65
XProgramming
  • Planning
  • Designing
  • Coding
  • Testing

of a slice
2-6 weeks
66
XProgramming
  • No global up front planning
  • Slices (meaningful slices) defined with the
    customer
  • Created quickly (2-6 weeks)
  • Accepted by the customer
  • ? Early feedback and impact on the
    requirements
  • Pair programming !!

67
XProgramming
  • Planning
  • User stories are written.
  • Release planning creates the schedule.
  • Make frequent small releases.
  • The project velocity is measured.
  • The project is divided into iterations.
  • Iteration planning starts each iteration.
  • Move people around.
  • A stand-up meeting starts each day.
  • Fix XP when it breaks.

68
XProgramming
  • Designing
  • Simplicity
  • Choose a system metaphor.
  • Use CRC1 cards for design sessions.
  • Create spike solutions (for difficult problems)
    to reduce risk.
  • No functionality is added early.
  • Refactor whenever and wherever possible.
  • 1 Class-Responsibility-Collaboration

69
XProgramming
  • Coding
  • The customer is always available.
  • Code must be written to agreed standards.
  • Code the unit test first.
  • All production code is pair programmed.
  • Only one pair integrates code at a time (CVS).
  • Integrate often.
  • Use collective code ownership.
  • Leave optimization till last.
  • No overtime.

70
XProgramming
  • Testing
  • All code must have unit tests.
  • All code must pass all unit tests before it can
    be released.
  • When a bug is found tests are created.
  • Acceptance tests are run often and the score is
    published.

71
XProgramming
  • Documentation is a planned task and the customer
    pays for it (some documentation must be
    integrated in the source code)
  • Teams are from 2 to 12 persons
  • A CVS (concurrent versioning system) is of course
    mandatory

72
XProgramming
http//www.extremeprogramming.org
73
TDD
74
TDD Test Driven Development
  • Write a test before any real code writing
  • On Eclipse
  • JUnit 1.3.8 Java 1.4
  • JUnit 4 Java 5.0 with annotations

75
TDD Test Driven Development
  • Documentation Eclipse
  • Help gt Help Contents gt Java Development User
    Guide gt Getting Started gt Basic Tutorial gt
    Writing and running JUnit tests (1.3.8)
  • Help gt Help Contents gt Java Development User
    Guide gt Whats new gt JUnit Toolings (4)
  • (http//www.junit.org) ? JUnit 4.0 in 10 minutes

76
TDD
  • Create a Java project as usual
  • Project gt Build Path gt Add Libraries gt JUnit 4
  • Right-click the class that will be under test
    (possibly with an empty method) gt New gt
    JUnit Test Case (creates a case of the version
    entered into the build path)
  • Define a package that is going to contain the
    tests

77
TDD
  • Edit the test class
  • Create an instantiation of the Class under test
    in the _at_BeforeClass method (once for all methods)
    or in the _at_Before method (once for every method)
  • Put one test (CTRL-space) per test method. If you
    put several tests, they will not be identified
    separately when there is an error.
  • The message in an assertion is displayed if there
    is an error
  • It is possible to check the kind of Exception
    returned by the method under test (see doc)

78
TDD
package unitTests import static
org.junit. public class ComputationTest1
static example.Computation computation
null / This method is executed only
once before all tests Here, it creates an
environment to test the modules
/ _at_BeforeClass public static void setUp()
throws Exception computation new
example.Computation() computation.setResult(0)

79
TDD
  • package unitTests
  • import static org.junit.Assert.
  • import org.junit.After
  • import org.junit.Before
  • import org.junit.Test
  • import org.junit.BeforeClass
  • public class ComputationTest1
  • static example.Computation computation null
  • /
  • The following method is repeated before every
    test
  • /
  • _at_Before
  • public void setUpRepeated() throws Exception
  • computation new example.Computation()
  • computation.setResult(0)
  • . . .

80
TDD
. . . _at_After public void tearDown() throws
Exception _at_Test public void
testComputation() _at_Test public void
testAdd1() computation.add(7) // To show
an error in a test, the next check is incorrect
! assertTrue("Error 1 of computation",
computation.getResult()6) _at_Test public
void testAdd2() computation.add(-12) assert
True("Error 2 of computation", computation.getResu
lt()-5)
81
TDD running the tests
  • Select some test classes or the test package
  • Right click the selection gt
    Run As gt JUnit Test
  • The result is displayed in the view JUnit (same
    window as the Package Explorer)

82
Exercice
Develop a class with a method that counts the
lines that are not empty nor just contain
comments, creating tests for each new code
increment. As soon as you have a idea to start
the problem, create a test, implement this first
part and test it. For each new increment, do the
same. Dont think too much beforehand, just try
and test, but keep all tests and improve/refactor
your code Use pair programming
/ This is a test program with 5 lines of
code /////// Slightly pathological
comment ending... public class Hello
public static void main(String args) //
comment // Say hello System./wait/out./
for/println/it/(Hello/)
83
Design Patterns
http//en.wikipedia.org/wiki/Design_Patterns http
//en.wikipedia.org/wiki/Design_pattern_(computer_
science) See also anti-patterns in Wikipedia and
http//ltiwww.epfl.ch/petitp/GenieLogiciel/
PointCounterPoint.pdf
84
Design Patterns
Christopher Alexander is an architect noted for
his theories about design. He produced and
validated a pattern language designed to empower
any human being to design and build at any scale.
The concept of design patterns has been reused
in IT by E.??Gamma, R Helm, R. Johnson and J.
Vlissides also known as the Gang of Four or GoF.
They have sold 500.000 copies of their
book. Abstract factory, Adapter, Composite,
Decorator, Factory methods, Observer, Strategy,
Template method E. Gamma is currently heading
the Eclipse project Other authors have written
books about patterns
85
Design Patterns (basic concepts)
class SomeClass extends SuperClass private
String str public String getString()
return str
Signature All signatures type (or subtype) The
whole class (subclass or derived class) The
subclass inherits (extends) the superclass
86
Design Patterns
  • An object is an instance of a class
  • An abstract class has abstract operations
  • A concrete class is one that is not abstract
  • A concrete class that inherits an abstract class
    must override the abstract operations
  • A first-class operator or function is one that
    can be defined during the execution of a program,
    stored in a variable, passed as arguments to
    other functions, and returned as the values of
    other functions.

87
Inheritance / Composition / Forward
class SuperClass private String name public
String getName() return name class
InheritanceClass extends SuperClass
ci new InheritanceClass () ci.getName()
88
Inheritance / Composition / Forward
class SuperClass private String name public
String getName() return name class
CompositionClass SuperClass element
cc new CompositionClass() cc.element.getName()
89
Inheritance / Composition / Forward
class SuperClass private String name public
String getName() return name class
ForwardClass SuperClass element public
String getName() return
element.getName()
Cd new ForwardClass() cd.getName()
90
Delegation composition forward environment
  • class SuperClass
  • private String name
  • public String getName(DelegationClass env)
  • return env.xxxxxname
  • cd new
    DelegationClass()
  • class DelegationClass
    cd.getName()
  • SuperClass element
  • String xxxxx
  • public String getName() return
    element.getName(this)
  • // see GoFs state design pattern for
    an example

91
Two GoF principles
  • Program to an interface, not an implementation
  • Favor object composition over class inheritance

92
Declare interfaces, not classes,
  • public interface Interface
  • public String method()
  • public class SubClass implements Interface
  • public String method()
  • return null

BUT
93
debugging and maintenance become difficult
!Example
  • public class Application
  • Interface intf
  • public static void main(String args)
  • Application a new Application()
  • a.intf new SubClass()
  • a.execute(args)
  • void execute(String args)
  • intf.method()

Where do I find the source of method() ?
94
Note that you dont need to implement a new
interface to insert new attributes !! If
an attribute is added to an object, it does not
disturbs the other uses of the object.Refactorin
g may also be called to rescue !
95
The GoF patterns
Design Patterns Elements of Reusable
Object-Oriented Software, E. Gamma
96
Inheritance (in GoFs book)
identical
97
Singleton
Class2
Class1
Class3
Singleton
Only one singleton is instantiated One does not
know the order in which the Classi are
instantiated All Classi are not always present,
they have no references to each other and there
may be other such classes later Who does create
the Singleton ?
98
Singleton
public class ClassicSingleton private static
ClassicSingleton instance null protected
ClassicSingleton() // Exists only to defeat
instantiation public static
ClassicSingleton getInstance() if (instance
null) instance new ClassicSingleton()
return instance used in
place of new ClassicSingleton() // from
Javaworld
99
Singletons
  • Global variable !
  • Dont overuse them !
  • Only for data that are meaningful in the whole
    program
  • Not more than a few singletons in a program

100
(Complex) example of use
Threadlocal is a singleton that may be attached
to the current thread, the one that executes the
code of the current method. It is managed by the
JVM.
101
TheadLocal singleton
The class introduced into ThreadLocal can be
accessed in the following way
x HolderObject.get()
x HolderObject.get()
x HolderObject.get()
Thread1
Thread2
y HolderObject.get()
y HolderObject.get()
Thanks to the JVM, there is one singleton per
thread, x ! y, x always the same,
y always the same
102
(Complex) example of use
class HolderObject public static
ThreadLocalltMyObjectgt // definition
of an attribute currentObject new
ThreadLocalltMyObjectgt() protected
synchronized MyObject initialValue() return
new MyObject() public static MyObject
get() // any object can be kept in
ThreadLocal return currentObject.get() //
At the initialization, the object ThreadLocal
calls method initValue(), // defined by the
developer. This method returns an object. // This
object is then stored in ThreadLocal located in
currentObject. // Moreover, the JVM saves and
restores this object at each context switch
103
(Complex) example of use
class HolderObject public static
ThreadLocallt HolderObject gt currentObject
new ThreadLocallt HolderObject gt() protected
synchronized HolderObject initialValue()
return new HolderObject ()
public static HolderObject get()
return currentObject.get() Type
userAttribute initval // Usually the
object that is stored is the HolderObject itself
104
ThreadLocal
Can be used to replace parameters in a method
call, but in very specific situations, such as
  • Process support (task control block,
    semaphore, identifier)
  • Transaction manager (EJB3)

105
Exercice 2
  • Créer un object dont la méthode run est exécutée
    sur un thread.
  • Cette méthode contient une boucle infinie et
    affiche toutes les secondes un identificateur
    unique mémorisé dans le singleton ThreadLocal du
    thread.
  • Créer deux de ces objets et lancez-les sur deux
    threads.
  • Pour générer des identificateurs uniques,
    utiliser un deuxième singleton (global celui-là).
  • Attention, sa méthode doit utiliser synchronized !

106
Singleton retournant un ID unique
class Singleton static Singleton single
null int i 10 public static Singleton
instantiate() if (single null)
single new Singleton()
return single public int get()
return i
Quand on a obtenu un ID, il ne faut plus utiliser
le singleton depuis le même thread, car les
autres objets feront changer le contenu de la
variable utilisée pour générer les Ids. new
Thread(new Thr()).start() new Thread(new
Thr()).start()
107
Creation dun objet ThreadLocal
class HolderObject public static
ThreadLocalltHolderObjectgt currentObject
new ThreadLocalltHolderObjectgt() protected
synchronized HolderObject initialValue()
return new HolderObject() public
static String getString() return
currentObject.get().str public static void
setString(String s) currentObject.get().str
s String str null
Un singleton par thread. On peut faire plusieurs
fois getString() dans chaque thread. Chaque
thread verra sa propre valeur.
108
Class or object adapter
Goal The class adapter implements a new
interface that provides a new functionality or an
existing functionality under a new name. In the
class adapter, the code that implements or
support the new functionality is called from an
auxiliary object that extends the object with the
available functionality. The object adapter
delegates the call to the available object.
109
Design Pattern Adapter (Inheritance /
Composition / Delegation)Interface
Required interface
Existing class
client
Adapter Just forwards the calls
110
Design Pattern Adapter
Required interface
Existing class
client
Two different possibilities
Adapter Just forwards the calls
Existing object
Also possible
111
Java implementation of a class adapter
/ Double Linked List / class DList public
void insertTail (Object o) ...
interface Stack void push (Object o)
/ Adapt DList class to Stack interface / class
DListImpStack extends DList implements Stack
public void push (Object o) insertTail
(o) //
forwards the calls
Adapter
112
Java implementation of a object adapter
/ Double Linked List / class DList public
void insertTail (Object o) ...
interface Stack void push (Object o)
/ Adapt DList class to Stack interface / class
DListImpStack implements Stack DList dl new
DList () public void push (Object o)
dl.insertTail (o)
113
Composite tree structure(one must be able to
walk through and add/remove groups or leaves in
the same way)
super group
Model of a diagram for a graphical application
group
square
line
circle
square
114
Composite
115
Implementation of the Composite
abstract class GraphicComponent abstract
public void print()
class CompositeGraphic extends GraphicComponent
private ArrayListltGraphicgt mChildGraphics
new ArrayListltGraphicgt() public void print()
for (Graphic graphic mChildGraphics)
graphic.print() Group
class Ellipse extends GraphicComponent public
void print() System.out.println("Ellipse")
Leaf
- All nodes are GraphicComponent with a print()
method - root.print() prints all leaves
116
Composite object diagram
super group
group
square
line
circle
square
Each object extends abstract class
GraphicComponent to make all objects compatibles
117
Composite other implementation details
  • Parent references may be handled
  • But if parents are multiple reverse path
    ambiguous ? Flyweight

118
Composite other implementation details
  • Where to define the children list and the
    getChild method ?
  • Component class (abstract class)
  • all elements similar (transparency)
  • but one may try to retrieve a child from a leaf
  • Composite class
  • one can check that elements are retrieved only
    from composite (safety)
  • But elements are dissimilar

119
Decorator
BufferedReader br new BufferedReader(
new InputStreamReader( new
ByteArrayInputStream( A
text to read.getBytes() )
) )
120
Decorator (class diagram)
121
Decorator
  • More flexibility than inheritance
  • Several identities (addresses) !
  • Keep interface simple
  • Decorators abstract class optional
  • For more complex cases ? Strategy

122
Decorator (object diagram)
WindowDecorator Window decorWindow Constructor(x)
decorWindow x
x new HScrollDecorator (new VScrollDecorator
(new SimpleWindow()))
123
Decorator
HScrollDecorator Constructor(x)
super(x) draw()
VScrollDecorator Constructor(x)
super(x) draw()
SimpleWindow draw()
public void draw() drawHorizontalScrollBar()
decoratedWindow.draw()
public void draw() drawVerticalScrollBar()
decoratedWindow.draw()
124
Decorator
HScrollDecorator Constructor(x)
super(x) getDescription()
VScrollDecorator Constructor(x)
super(x) getDescription()
SimpleWindow getDescription()
public String getDescription() return
decoratedWindow.getDescription() ",
including horizontal scrollbars"
public String getDescription() return
"simple window"
public String getDescription() return
decoratedWindow.getDescription() ",
including vertical scrollbars"
125
Decorator (without the intermediary
abstract classes)
HScrollDecorator Window decorWindow Constructor(x)
super(x) decorWindow x
VScrollDecorator Window decorWindow Constructor(x)
super(x) decorWindow x
SimpleWindow
126
Façade(simply relays calls to a set of
methodsan example is the Session Enterprise Java
Beans)
Facade
127
Bridge (avoids the following situation)
One must create two distinct sources, but their
sole difference is extends Window
versus extends NewWindow Two hierarchies
interleaved
128
Bridge (the red-blue lines)
OS independent hierarchy abstract class
Either red or blue is instantiated, at run time
OS Implementation
129
BridgePatternExample.java(as in the CVS, project
Patterns)
DrawingAPI drawCircle()
DrawingAPI1 drawCircle()
Shape drawingAPI resizeByPercentage()
ltltexclusifsgtgt
DrawingAPI2 drawCircle()
CircleShape draw()
130
Factories
  • Abstract Factory
  • The client gets a factory corresponding to a
    specified domain and then generates objects by
    calling it. All generated objects belong to the
    specified domain.
  • Factory Method
  • The client gets objects that are created
    according to some individual characteristic.The
    objects of the same application may belong to
    different domains.

Abstract factories are implemented with the help
of factory methods !
131
Abstract Factory
ltltcreate objectgtgt
ConcreteWindow1
ConcreteWindow1
ltltcreate objectgtgt
Of course the factories also inherits a common
interface, not shown here
132
Abstract factory (with interfaces)
Client
ltltcreategtgt
AbstractProductA
ConcreteProductA1
ConcreteProductA2
AbstractProductB
ConcreteProductB1
ConcreteProductB2
133
Factory Method
Client
create object of type x or y
ConcreteCreator factoryMethod(param) // knows
from param // which object to build //
xx.jpg / xx.gif
The same factory creates different objects
134
A Simple Factory Method Pattern
class Complex public static Complex
fromCartesian(double real, double imag)
return new Complex(real, imag) public
static Complex fromPolar(double rho, double
theta) return new Complex(rho
java.lang.Math.cos(theta), rho
java.lang.Math.sin(theta)) private
Complex(double a, double b) // ...
One method for each kind of object because it is
not possible to differentiate them by their
parameters.
135
Exercice 3
  • Créer une factory qui génère les composants
    suivants
  • Factory de fenêtres GUI
  • Factory d'objets qui utilisent la console
    d'Eclipse
  • La factory à créer est spécifiée dans une
    propriété
  • Les méthodes read du GUI et de la console sont
    bloquantes

136
Properties
  • // From the user properties
  • Properties myProperties new Properties()
  • FileInputStream
  • in new FileInputStream("myProp.properties")
  • myProperties.load(in)
  • in.close()
  • String dType myProperties.getProperty("displayTy
    pe")
  • // From the system properties
  • dtype System.getProperty("terminalType")

137
Synchronisations of threads
Thread 2
Thread 1
Object semaphore new Object() synchronized
(semaphore) semaphore.wait() synchronized
(semaphore) semaphore.notify()
1
suspended
2
3
If the call to notify() is done before the call
to wait() the wait() will wait the next call to
notify(). One should thus memorize the signal in
an attribute
138
Java Reflection
Paramètres (type, puis valeurs)
Instanciation String dType
"pack.Classname" Class dFactoryClass
Class.forName(dType) dFactoryClass.newInstanc
e() Appel d'une classe statique Class
dFactoryClass Class.forName(dType) Method
meth dFactoryClass.getMethod("getDisplayFactory"
, new Class0) DisplayFactory dFactory
(DisplayFactory)meth.invoke(null, new Object0)
Objet sur lequel la méthode est appelée (pas
d'objet ici, donc appel statique)
139
Drawback of Reflection
  • The availability of the class called in by
    reflection is only checked at runtime.
  • In order to clean an application, an IT team in a
    bank had eliminated all programs that had not
    been used for 6 months. At the December, 31
    closure, the programs had been destroyed ..

140
Flyweight(poids mouche, poids plume)
  • the program must handle lists containing many
    pieces
  • many of them are similar
  • using an object for each one would use up much
    memory space
  • a typical example is a text, in which each letter
    has specific parameters (font, face, size)

141
Flyweight
(flyweight pool)
HashMapltSpecialChargt
H Arial
L Times
E Times
O Arial
ArrayList ltSpecialChargt text (only pointers)
get returns the pointer to the SpecialChar, and
creates it if it does not exist already.
142
Flyweight
The GoF book describes the flyweight within a
hierarchy, but the hierarchy is independent from
the flyweight pattern. The Flyweight is used only
at the line level.
page
paragraph
paragraph
paragraph
line
line
line
line
143
FlyweightExample.java(as in CVS, project
Patterns)
GraphicCharFactory pool get(character, fontFace)
GraphicChar String fontFace printAtPosition(c, x)
ltltHashMapgtgt
FlyweightExample text main()
ltltArrayListgtgt
144
Observer
call
Each time the subject is called, it calls a
method in all the observers. Thus at the end of
each method called in the subject, there is a
call to the list of observers. The observer are
registered, sometimes by themselves The observers
must of course have a common interface. They are
also called listeners!
call
call
Subject
Observer
Observer
145
Observer
Subject void notify() for (observer o
pool) o.update()
Event
146
Observer
  • Observer
  • update()
  • it often register itself in the subject
  • Subject
  • notify()
  • addObserver()
  • removeObserver()

147
Template (simple use of inheritance)
Algorithm expressed as a sequence of
operations. These operations must be replaced
easily in the source
operation 1 operation 2
148
Template Method (trivial)
AbstractClass templateMethod primitiveOperation1
primitiveOperation2
ConcreteClass primitiveOperation1 primitiveOperat
ion2
Different concrete classes implement different
algorithms with the same sequence of operations
149
Strategy
  • A user class requires one algorithm chosen among
    a set of algorithms for its execution
  • The algorithm is performed within some context,
    which contains the data.
  • At initialization time, the current algorithm is
    set and then called by delegation
  • Template with delegation
  • Similar to bridge (Bridge ? structure
    Strategy ? behavior)

150
Strategy
  1. Set the algorithm reference in the context
  2. The algorithm is called from the context
  3. The algorithm may have access to the context

Client
ltlt interface gtgt Strategy algorithm()
Context currentAlgorithm contextInterface()

151
Strategy (usage)
// Three contexts following different
strategies context new Context(new
ConcreteStrategyA()) context.execute()
context new Context(new ConcreteStrategyB()
) context.execute() context new
Context(new ConcreteStrategyC())
context.execute()
152
Builder (similar to the strategy)
Builder
ltlt interface gtgt TextConverter ConvertChar(char) C
onvertFontChange() ConvertParagraph()
RTFReader builder ParseRTF()
TeXConverter ConvertChar(char) ConvertFontChange(
) ConvertParagraph() getTeXText()
ASCIIConverter ConvertChar(char) getASCIIText()
TextWidgetConverter ConvertChar(char) ConvertFont
Change() ConvertParagraph() getTextWidget()
while (getNextToken) switch (token)
case CHAR builder.convertChar(token)
break case FONT
builder.convertFontChange(token) break
case PARA . . .
153
Builder
ltlt interface gtgt Builder buildPart()
Director builder Construct()
ConcreteBuilder buildPart() getResult()
154
Chain of responsibility
  • This pattern allows a request to pass along a
    chain of objects until one of them handles it,
    thus giving multiple objects a chance to handle
    the request.

155
Chain of responsibility
aConcreteHandler successor
anotherConcreteHandler successor
156
Chain of responsibility
successor
Client
157
Command
  1. First class operation
  2. The command is provided with the object that must
    be processed
  3. The command may be stored and performed later

158
Command Pattern
ConcreteCommand_3 document execute()
ConcreteCommand_2 document execute()
ConcreteCommand_1 document execute()
The command is defined within an object. It can
thus be passed over to other objects, it can be
stored in a list, called at any time later and so
on. It is thus a mean to create a command as a
first class operation. The command also binds a
command to a receiver (document)
159
Command Pattern undo
  • Useful to create undoable commands
  • The command receives the state of the document
    before the command is executed
  • It defines an undo function that restores the
    previous state
  • The commands are kept in a list, in the order of
    their execution
  • Can be combined with the memento pattern

160
Command Pattern
3
2
ltltcreate and add commandgtgt
ltltcreategtgt
1
The commands can be stored in invokers, as in the
observer pattern, but here, the command contains
a reference to a document. new
ConcreteCommand(receiver)
161
Command when to use it
  • A document is read and then operations triggered
    by menu items are performed when a user clicks
    them (callback, listener)
  • One must prepare a context and have operations
    performed at a later time
  • Support undo (stack the commands)
  • Support transactions (which may have to be undone)

162
Memento
  • Object used to save and later restore a state

Originator state setTo(Memento m) createMemento()
Memento state getState() setState()
Caretaker state setTo(Memento m) createMemento()
return new Memento(state)
state m.getState()
  • The caretaker should no see the state, it must
    only store and retrieve it.
  • Can be used by a Command object to maintain the
    state of the undo.

163
Prototype
  • Several objects with few variations must be
    created
  • Their attribute values are only known at run time
  • One instantiates a prototype and then clones it

164
Cloning objects in Java
(not a pattern, but used in prototype)
public class ToBeCloned implements Cloneable
String s xxx" int i new int
0,4,2 public ToBeCloned clone()
try
// copies the simple attributes
ToBeCloned temp (ToBeCloned ) super.clone()
temp.i i.clone()
// an array must be cloned explicitly
return temp // - Java
defines clone() in arrays catch
(CloneNotSupportedException cnse)
return null // for special
constructs, the program must copy the contents
explicitly
165
Prototype
ltlt interface gtgt Prototype clone()
Client operation()
166
Proxies
  • Remote proxy(proxy that forwards the calls to an
    object located in a remote site)
  • Virtual proxy(e.g. an object that represents a
    figure that is loaded only when the figure
    appears on the current page. Used for
    optimization purpose)
  • Protection proxy(an object that intercepts all
    calls to an object and checks if the caller has
    the right to call it)
  • Handle(e.g. to maintain the number of links to
    the object to destroy it when the last link has
    been freed, referencing a persistent object to
    load it when it is first referenced or to map it
    on a key, to lock it, and so on)

167
Proxy
aProxy realSubject
Client request()
168
Iterator
Iterator
ltltcreategtgt
169
Iterator
  • Provides a way to traverse an aggregation
    according to different policies, without
    introducing the policy into the list object
  • Filtering can be introduced
  • The iterator references the list and vice-versa
    a creator method in the list must connect the two
    ( can be implemented as a factory)

170
Iterator object diagram
Client
AbstractList createIterator() count() append(Obje
ct) removeItem(Object) . . .
Iterator first() next() isDone() currentItem() re
moveItem()
List
ListIterator
Skip
SkipList
It is important to have a remove operation within
the iterator, otherwise one cannot remove an
element during the scan, because if the current
element is removed without the iterator knowing
it, it would not skip the missing element.
171
Iterator class diagram
Client
Aggregate createIterator()
Iterator first() next() isDone() currentItem()
ConcreteIterator
ConcreteAggregate createIterator()
return new ConcreteIterator(this)
172
Mediator
  • Many objects (called the colleagues) have
    connections between them
  • The connections between the objects are managed
    by a central object the mediator

173
Mediator implementation
  • The accesses to the colleagues may be implemented
    according to the observer pattern or simply by
    delegation
  • The colleagues may pass a reference to themselves
    (this) within the call to the mediator, to
    identify the callers

174
Mediator an object diagram
Mediator
Colleague
ConcreteMediator
ConcreteColleague1
ConcreteColleague2
175
State, Interpreter and Visitor Patterns
  • These patterns will be used in relation with the
    analysis of languages (XML or other)
  • We will thus study SAX, DOM and Javacc (Java
    compilers compiler) in relation with these
    patterns.
  • (See http//www.epflpress.org/Book_Pages/petitpier
    re.html)

176
State Pattern
previous
next
enter
0
2
ignore
display_francs
1
display_euros
177
State Pattern (one method to handle all actions)
ltlt interface gtgt State handle()
Context state request()
The handle() method determines the nature of the
event that has occurred. If it is not foreseen in
some state, the method takes some corrective
action.
178
State Pattern (one method per action)
Context state action1( ) action2( ) action3( )

State action1( ) action2( ) action3( )
The action is determined by the event generator.
If it is not foreseen in some state, the default
action is called. The later ignores the action or
handles the error.
179
State Pattern (State interface)
abstract class State public void
action1(Context context) public void
action2(Context context) public void
action3(Context context)
180
State Pattern (context)
class Context State state
First.getState() public void
changeState(State s) state s
public void action1()
state.action1(this) public void
action2() state.action2(this)
public void action3()
state.action3(this)
181
State Pattern (State object)
class Second extends State static State
state null public static State getState()
if (state null) state
new Second() return state
public void action2(Context context)
System.out.println("action 2") // go to
First State context.changeState(First.getS
tate()) public void action3(Context
context) System.out.println("action
3") context.changeState(Third.getState())

182
State Pattern (based on a switch)
class Context3 enum State a, b, c
State state State.a public int number
public void handle(char inp) switch
(state) case a if (inp
'1') System.out.println("action
1") state State.b
break case b
if (inp '2')
System.out.println("action 2")
state State.a else if (inp
'3') System.out.println("action
3") number 0
state State.c
break . . .
Not official, but more efficient use a switch
(in theory, a state is a position in a program
and the set of all the values of its variables)
183
A SAX Parser with the State Pattern can be used
to read XML files.
184
XML EXtensible Markup Language
lt!-- A comment --gt ltpersongt
ltfirstNamegtRobertlt/firstNamegt ltname/gt lt!--
empty --gt ltaddress category"private"
duration"permanent"gt ltstreetgtCarrigton
alleelt/streetgt lttowngtPhiladelphialt/towngt
lt/addressgt lt/persongt amp
apos lt gt quot
185
DTD Data Type Definition(defined in the XML
standard)
lt!ELEMENT person (firstName, name, address)gt
lt!ELEMENT firstName (PCDATA)gt lt!ELEMENT name
(PCDATA)gt lt!ELEMENT address (street,
town)gt lt!ELEMENT street (PCDATA)gt lt!ELEMENT town
(PCDATA)gt lt!ATTLIST address category
CDATA IMPLIED duration
(permanenttemporary) "temporary gt PCDATA
parsed character data (the gt are translated)
186
Commande ATTLIST
lt!ATTLIST symbolOfTheElement symbolOfTheAttribute
1 attributeType1 characteristic1 symbolOfTheAttri
bute2 attributeType2 characteristic2 gt
187
attributeTypes possibles dans une DTD
CDATA "xxx yyy quot NMTOKEN "v1.2 without
space NMTOKENS "v1.2 xxx www a list of
tokens ID "aUniqueId this ID should appear
only once in the whole XML
file IDREF "anExistingID there should be the
same ID somewhere in the XML
file IDREFS "anID anotherOne a list of
IDREF Enumeration (Monday Tuesday
Wednesday) NOTATION see the standard ENTITY see
the standard
S
Write a Comment
User Comments (0)
About PowerShow.com