Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
UML and
Design patterns
Jean-Philippe Ulpiano
Presentation of UML
UML provides the ability to describe a program through:● Behavioral diagrams:
Use case, Activity, Collaboration, State Machine, Sequence diagram.
● Structural diagrams:
Class Diagram, Object diagram, Component Diagram, Package diagram.
UML what for ?● Create Documentation and keep it up to date● Extract classes out of a concept:
– Analyze Concepts with a Use Case diagram
– Analyze Timings with a Sequence or a Communication Diagram
– Analyze the architecture with a Component Diagram or Package Diagram
– Extract classes out of the architecture: visual process improves design quality.
– Perform code generation and automatically create empty unit-test bodies (with self written script).
Examples● Most of the examples here are provided as original
ideas from on a small Arduino board based car I created for my son.
● Examples are kept simple such that ideas behind the diagram are clear.
● The car is programmable with a small keyboard (Left, Right, Front and '*').
● The key '*' starts the car and makes it following the programmed path.
● Pressing again '*' starts again the car.
● Pressing another key, clears the programs and starts saving a new one.
The Use Case diagram 1● Use Case diagrams is usually not used to
describe behaviors and processes.● It describes the associations between a
number of use cases and the involved actors: that is what will be delivered by the system.
● It is comprised of only a few very intuitive elements.
The Use Case diagram 2● In a use case diagram, all stakeholders involved in a
procedure are Actors.
● A use case specifies a number of actions executed by a system and which lead to an important result for an actor.
● Use cases and actors have a certain relationship with one another. Relationships are modeled with lines.
● The creation of an Use case diagram is an iterative process: start creating boxes and circles, analyze, update, connect, reconnect, …
● An actor specifies the role played by an external entity that interacts with the subject: a human user of the designed system, some other system or hardware using services of the subject.
The Use Case diagram 3
● An actor can participate to various use cases. A use case can be accessed by various actors.
● Actors should only be external entities. A technical way to achieve a result is not an actor.
● Do not mix role and concrete entities. An external entity can play various roles and modeled by various actors.
● One role can be played by various concrete external entities but modeled by one actor.
The Use Case diagram 4 (Stereotypes)
● Use cases may also be associated with the <<include>> (must relationship) and <<extend>> (can relationship) stereotypes.
● A use case making no sense on its own is an <<include>> use case. It can as well provide a behavior that is common to other use case.
● <<extend>> represents additional behavior, new functionality being added.
The Use Case diagram 5 (a complete example)
Use case diagram 6
Next diagram
● Usually next diagram should be a Communication or Sequence diagram.
● The analyze of the dynamic helps extracting classes out of a concept.
● Some basic dynamic can however be represented on the Use Case diagram thus avoiding this next step.
Modelisation of the dynamic● Use cases represent actions and reactions
between an external actor and the system.● Two different diagrams represent different
aspects of the dynamic:– The sequence diagram details temporal
aspects.
It is used to depict work flow, message passing and how elements (life lines) in general cooperate over time to achieve a result.
– The communication diagram shows a spatial representation of the system.
Communication diagram 1
● Communication diagram corresponds (i.e. could be converted to/from or replaced by) to a simple sequence diagram without structuring mechanisms such as interaction uses and combined fragments.
● It is oriented to a spatial representation of objects rather than timing one.
● All messages are numbered.● In UML 1.x this diagram was called the
Collaboration Diagram.
Communication diagram 2
Communication diagram 3
● The communication diagram can be easier to read for a non developer and is sufficient for rough communication description.
● It lacks however much of the fragments available for the sequence diagram.
● A sequence diagram is useful when some aspects between the communication of the components require deeper analyze.
The sequence diagram 1
● It describes the dynamic of the system.● The diagram consists in sending messages
between lifelines and using fragments to control branches, loops and sub diagrams.
● Each of these message is sequentially numbered starting from 1.
● Refrain from creating huge diagram.● Rather use several such diagrams splitting
the system in sub functions.
The sequence diagram 2
The sequence diagram 3
Connect with end points Creation / destruction of objects
The sequence diagram 4● Using Manage Key saving reference diagram.
The sequence diagram 5● Split sequence diagrams: This is the Manage
Key Saving sequential diagram.
The sequence diagram 6● Combined fragments
– Alt fragment should contain an else (If with 2 paths: something will be executed):
– Opt fragment should not contain an else (One or several independent if):
The sequence diagram 7
● Looping with or without condition:
● Breaking a loop:
The sequence diagram 8
● Parallelism
● Negation
The sequence diagram 9
● The strict sequencing guarantees that the order of the messages is respected: A message of a part is sent only if the message of the previous part are sent.
● The vertical coordinate of the contained fragments is significant throughout the whole scope of the combined fragment and not only on one lifeline.
The sequence diagram 10Weak sequencing is defined by the set of traces with these properties:
● The ordering of occurrence specifications within each of the operands is maintained.
● Occurrence specifications on different operands from different life lines may come in any order.
● Weak sequencing reduces to a parallel merge when the operands are on different lifelines.
● Weak sequencing reduces to strict sequencing when the operands work on the same lifeline.
The sequence diagram 11
● 1.0 can be run in parallel to 1.1 and 1.2● 1.1 and 1.2 must be run in a strict sequencing
The sequence diagram 12
See here for more information on the sequence diagram:
http://www.uml-diagrams.org/sequence-diagrams.html
Next diagram● Use Case diagram: Understand the concepts of the new
system: what do we really want, how should it roughly work ?
● Communication and Sequence diagram: Understand how the complex components (not the full system) of the system communicate together
– Requires to decompose messages
– Find the destination of each message
– This decomposition automatically starts extracting components
● Define the architecture through Components, Composite or Package diagram to better analyze the structural part of the architecture
● Note that if the system is not too complex it is possible to move directly to the class diagram
Component, Composite and Package diagram● Component diagram
– Easily represent SOA (Service Oriented Architecture)
– Flexible enough to represent other kind of accesses that are not SOA (using it as a composite diagram)
● Composite diagram
– Mid way between Class and Component diagram: however does not provide components: Thus Component diagram might be a better alternative for higher abstraction.
● Package diagram
– A package represents a directory
– A package can contain classes, use case diagram, component diagrams
– Accesses inside a package are similar to Java package accesses
– Packages should have a low coupling between each other and a high coherence inside each of them.
Component diagram 1
● A component is a black box providing interfaces
● A component diagram has a higher level of abstraction than a class diagram
● A port is an interaction point of a component, it is associated to one or many provided or required interfaces
● The interface becomes a child element of the component: it cannot exist independently
● A component is implemented by one or more classes
Component Diagram 2
● Component diagram using ports:● Component diagram can display
classes and interfaces
Component Diagram 3
● Flexibility of the component diagram– Display non SOA with such a diagram is
straightforward.
– This diagram is an important step to extract classes.
Next diagram● The Component or Class diagram might
reveal the need of a state machine.● The logical next diagram would then be a
State diagram.● The State diagram can be further described
with an Activity diagram.● At the end, the creation/iteration of a Class
diagram will be greatly simplified thanks to the previous iteration steps.
State diagram 1● Not documented state machines are
particularly difficult to maintain.● A state can be inactive:
Waiting for other signals to wake up the state.
● It can be active: An activity is the execution of methods and the
interaction with other objects. It is best described with the activity diagram.
● The life cycle of an object starts with an initial state and can end with one or many final states (or not end at all).
State diagram 2Possible events
● CallEvent Call a method.
● ChangeEventA change happened in the system.
● TimeEventTime based event (relative or absolute).
● SignalEventA signal happened to trigger a state.
● AnyReceivedEvent (all) Will trigger the state if no other event type rise at the
same time.
State diagram 3
● UML describes signals with classes.
● A signal is an instance of a class.
● Such classes have the stereotype “signal”.
● The parameters of the message are modeled by the attributes of the class.
● Such a representation allows to represent signals with a hierarchy.
● Parallelism is very easy to describe.
● Signals can be represented with a guard condition: SignalName[Condition]
State diagram 4
● See here 2 examples using 2 different notations:
State diagram 5
Activities can be associated to states. They can be specified as follow:● During a state● Crossing a transition● Starting or ending a state● In a state when an event occurred
State diagram 6● See here an example
Note that state diagram can be hierarchically created: A state machine can be described in a state.
Activity Diagram 1● Activity diagrams are used to model the behaviors of a system.
● The representation is similar to a simplified state diagram and will be used in the modelisation of:
– System behavior,
– Dynamic element interaction
● Flow of control is represented through sequences and conditions.
● The coordination occurs through:
– Action finished executing,
– Data availability,
– External event.
● An activity is a behavior represented as a flow of actions.
Activity diagram 2
This activity diagram represents the state Driving Car
Timing diagram
This diagram is rather adapted for real time systems.
Interaction Overview Diagram● An interaction overview diagram is a form of activity
diagram in which the nodes represent interaction diagrams.
● Interaction diagrams can include sequence, communication, interaction overview and timing diagrams.
● Most of the notation for interaction overview diagrams is the same for activity diagrams.
● For example, initial, final, decision, merge, fork and join nodes are all the same.
● However, interaction overview diagrams introduce two new elements: interaction occurrences and interaction elements.
Next diagram● The Class diagram is the next diagram.● To profit of this diagram many OOP rules must
be respected.● Creating classes without step backing to the
OOP rules (most of them defined in the last century) would result in a useless process.
● The OOP rules are there to help creating extensible and readable designs.
● These rules make this diagram is the most complex to design.
The class diagram 1● The class diagram represent the structure of
the program.● The classes are usually extracted out of
other diagrams: Use case, Timing like Sequence/Communication diagram, Component/Package diagram, State diagram.
● When designing keep always the 5 SOLID principles in mind to achieve an extensible class design.
● Rule NUMBER 1: Make your interfaces easy to use correctly and hard to use incorrectly.
The class diagram 2SOLID: principles of class design
SRP The Single Responsibility Principle One class should imply at most one reason for changes.Many responsibilities imply many axis of changes.
OCP The Open Closed Principle Open for extension, but closed for modification:Try extending a class instead of modifying it.
LSP The Liskov Substitution Principle Design by contract: Object references should be replaceable with instances of their subtypes without altering the correctness of a program.
ISP The Interface Segregation Principle Many client-specific interfaces are better than one general-purpose interface.
DIP The Dependency Inversion Principle Depend on abstractions, not on concretions.Avoid RTTI (Run Time Type Information): type_id, dynamic_cast.
Strive for loosed coupling design
The class diagram 3
● Once created, many UML program allow to perform code generation.
● Maintained class diagram generating code allow a much smoother extensibility of the design as long as SOLID principles are respected.
● SOLID principles can be better respected having a class diagram and not only source code.
● Some tool allow reverse engineering such that the diagram can be updated when source code is modified.
The class diagram 4
The class diagram 5Tips to achieve loose coupling:
● Prefer aggregation and composition over inheritance.
– Aggregation: Container relation without further constraints (Empty diamond on the composite side).
– Composition: The composite has ownership on the contained object (Filled diamond on the composite side).
● If virtual functions are needed, check if private inheritance makes sense (Private inheritance is another meaning for implemented in terms of).
● If the class relation ship is IS-A then public inheritance makes sense (Remember this is the strongest relation between two classes: always prefer a weaker relation if possible).
● Note that interfaces do not follow the IS-A recommendation: inheriting from an interface allows to share API.
The class diagram 6
The class diagram 7(From Scott Meyer)
void SetWidth(int width){ auto old_height = size.GetHeight(); size.SetWidth(width); assert(size.GetHeight() == old_height);}
Public inheritance asserts that everything that applies to base class objects (EVERYTHING!)
also applies to derived class objects (Liskov Principle).
The class diagram 8
Association class enables an Association to have attributes and operations (features).
This results in a hybrid relation with the characteristics of an Association and a Class.
A qualified association allows to provide a similar information but is rather used in multiple associations.
The object diagram
● It represents an instance of a class diagram at a specific point of time.
● Can be useful to display an initial condition.● The latest UML 2.5 specification does not
explicitly define object diagrams, but provides a notation for instances of classifiers (http://www.omg.org/spec/UML/2.5/).
The deployment diagram● Hardware devices, processors and software execution
environments (system Artifacts) are reflected as Nodes, and the internal construction can be depicted by embedding or nesting Nodes.
● Deployment relationships indicate the deployment of Artifacts.
● Manifest relationships reveal the physical implementation of components.
● Useful in DevOps activities:
https://puppet.com/blog/a-deployment-pipeline-for-infrastructure-a-devops-case-study-at-nbn
Design patterns● UML diagram are composed of behavioral and
structural diagrams.
● It is interesting to note that design patterns as described by the GoF (Gang of Four) are grouped in
– Creational (Builder, Factory, Prototype, …),
– Structural (Adapter, Bridge, Decorator, …),
– Behavioral (Command, Observer, Visitor, …).● In the meantime other types of design pattern appeared:
Concurrency patterns, Anti-patterns, J2EE Patterns, ...
● Design patterns are mostly described as class diagrams (structural diagram).
Builder, Factory PatternOften, designs start out using Factory Method (less complicated, more customizable, subclasses
proliferate) and evolve toward abstract factory, prototype, or builder (more flexible, more complex) as the designer discovers where more flexibility is needed. (GoF, p136)
Builder: Separate the construction of a complex object from its representation so thatthe same construction process can create different representations. (GoF, p110)
auto mySportCar = SportCar::Builder().
SetBlueColor(255).SetMaxSpeed(391).
SetAutomatic(false).Build();
Abstract Factories PatternProvide an interface for creating families of related or dependent objects without specifying their
concrete classes. (GoF, p99)
Prototype PatternPrototype does not require subclassing, but it does require an "initialize" operation. Factory method requires subclassing, but does not require initialization. (GoF, p116)
Prototype pattern refers to creating duplicate object while keeping performance in mind: instance creations requiring time as duplication (DB accesses) can be faster than instantiation.
The abstract class must have a method named clone or similar which will care of copying the class. It could provide a default implementation for the low level copy. The deepness of the copy depends on the requirements. A DB/GPS connectionwould certainly be shallow copied but some pointer information might need to be deep copied.
Adapter PatternConvert the interface of a class into another interface clients expect. Adapter lets classes work
together that couldn't otherwise because of incompatible interfaces. (GoF, p157)
Bridge PatternDecouple an abstraction from its implementation so that the two can vary independently. (GoF, p171)Note the similarities with the pImpl idiom used to break compilation dependencies: Bridge pattern is about
object-oriented design, while the PImpl idiom is about physical design of files.
These two parts can evolve independently
from each other as long as the contract
specified by the interface is respected.
m_WheelImp->GetStructureSolidity();
Decorator PatternAttach additional responsibilities to an object dynamically. Decorators provide a flexible
alternative to subclassing for extending functionality. (GoF, p196)This design pattern is also known as Wrapper: enclose an object in another one that adds
functionality to it. The enclosing object is called a decorator.
The method GetPrice defined in the interface must be kept on both sides.This pattern allows to extend a class in various directions
without risking an explosion of types such as: PeugeotRedSeat, PeugeotNonVeggySeat, ToyRedSeat, ...
auto seat1 = std::make_unique<PeugeotSeat>();auto decorated_seat1 = std::make_unique<RedSeat>(seat1.get());// Get the price of a Peugeot red seatstd::cout << decorated_seat1->GetPrice()
Command PatternEncapsulate a request as an object, thereby letting you parameterize clients with
different requests, queue or log requests, and support undoable operations. (GoF, p263)Commands are an object-oriented replacement for callbacks.
int main() {
Receiver receiver; PathDriveCommand pdc(&receiver); SavePathCommand spc(&receiver); InputSystem kbd;
kbd.OnKeyPressed('a', &pdc); // Check drive direction works kbd.OnKeyPressed('a', &spc);; // Save path kbd.UndoLastUndoableAction();}
Observer PatternDefine a one-to-many dependency between objects so that when one object changes state,
all its dependents are notified and updated automatically. (GoF, p326)for(auto const& obs: observers) obs.Update(new_volume);
After being informed of a change in the concrete subject, a concrete observerobject may query the subject for information if it is not provided as a parameter.
Visitor PatternVisitor lets you define a new operation without changing the classes of the elements
on which it operates. (GoF, p366)The Visitor pattern allows to separate an algorithm from an object structure (Wikipedia)
● You can define a new operation over an object structure simply by adding a new visitor.● The Visitor pattern makes it hard to add new sub classes of Element.● If the Element class hierarchy is stable, but you are continually adding operations or changing algorithms, then the Visitor pattern will help you manage the changes.
Declares a Visit operation for each class of the object structure.
Extension is easy for new visit operations stored in new classes.
Extension here is costly.
The end