object-oriented design layers. 2 layering mechanisms introduction to layering design principles...
TRANSCRIPT
Ob
ject
-Ori
en
ted D
esi
gn
LayersLayers
2
Ob
ject
-Ori
en
ted D
esi
gn
Layering MechanismsLayering Mechanisms
Introduction to layering design Introduction to layering design principlesprinciples
Determining when to use layersDetermining when to use layers The attention points when layeringThe attention points when layering Layering and PAC modelLayering and PAC model
3
Ob
ject
-Ori
en
ted D
esi
gn
Layered SystemsLayered Systems
Hierarchically organisedHierarchically organised A layer provides services to layer(s) A layer provides services to layer(s)
above itabove it A layer is a client to layer(s) below itA layer is a client to layer(s) below it Possible topological constraints Possible topological constraints
(opaqueness)(opaqueness) Limit interactions between adjacent Limit interactions between adjacent
layerslayers
4
Ob
ject
-Ori
en
ted D
esi
gn
Examples of layered Examples of layered SystemsSystems
Layered communication protocols Layered communication protocols (e.g. OSI)(e.g. OSI)
OS kernels (e.g. Windows, Chorus)OS kernels (e.g. Windows, Chorus) Database systems (e.g. ANSI/SPARC)Database systems (e.g. ANSI/SPARC) Many commercial apps use layers Many commercial apps use layers
modelmodel The agents in a PAC model!The agents in a PAC model!
5
Ob
ject
-Ori
en
ted D
esi
gn
Generic OS EnvironmentGeneric OS Environment
User-visible elements (layer 6)User-visible elements (layer 6) Specific application modules (layer Specific application modules (layer
5)5) Common services level (layer 4)Common services level (layer 4) OS interface level (layer 3)OS interface level (layer 3) OS (may itself be layered) (layer 2)OS (may itself be layered) (layer 2) Hardware (layer 1)Hardware (layer 1)
6
Ob
ject
-Ori
en
ted D
esi
gn
Typical Layers RegimeTypical Layers Regime
UI
Specific Applications
Common Services
OS Interface
OS
Hardware 1
2
3
4
5
6
7
Ob
ject
-Ori
en
ted D
esi
gn
Reasons for layered Reasons for layered SystemsSystems
Support designs based in increasing Support designs based in increasing levels of abstractionlevels of abstraction
Can partition a problem into smaller Can partition a problem into smaller piecespieces
Changes to a layer affect only a few Changes to a layer affect only a few layerslayers
Layers can be used interchangeablyLayers can be used interchangeably Reuse is supported Reuse is supported
8
Ob
ject
-Ori
en
ted D
esi
gn
Implementing layered Implementing layered SystemsSystems
We use Buschmann’s Layers patternWe use Buschmann’s Layers pattern Iterative process in general (‘yo-yo’)Iterative process in general (‘yo-yo’) Approximately 10 stepsApproximately 10 steps Other (Gamma) patterns may be Other (Gamma) patterns may be
usedused Approach is reusable (RT UML, Approach is reusable (RT UML,
component technology)component technology)
9
Ob
ject
-Ori
en
ted D
esi
gn
Some DefinitionsSome Definitions
A task is a responsibility of a given A task is a responsibility of a given layerlayer
A service is a set of functions offered A service is a set of functions offered by a layerby a layer
We speak of service layeringWe speak of service layering Each layer has interface functionsEach layer has interface functions A layer can be implemented as a A layer can be implemented as a
Black Box or White BoxBlack Box or White Box
10
Ob
ject
-Ori
en
ted D
esi
gn
More on ServicesMore on Services
Each layer can be viewed as a virtual Each layer can be viewed as a virtual machinemachine
A service is a programmable facility A service is a programmable facility of a virtual machineof a virtual machine
Examples of services: DB, comm, UIExamples of services: DB, comm, UI
11
Ob
ject
-Ori
en
ted D
esi
gn
What is ‘inside’ a Layer?What is ‘inside’ a Layer?
A layer populated by modules (e.g. A layer populated by modules (e.g. objects)objects)
Determine how to access module Determine how to access module interfacesinterfaces
Two main possibilitiesTwo main possibilities 1: ability to access all objects (White 1: ability to access all objects (White
Box)Box) 2: create a ‘contact’ for all modules 2: create a ‘contact’ for all modules
(Black Box)(Black Box)
12
Ob
ject
-Ori
en
ted D
esi
gn
Layer N is a black box for layer N + 1Layer N is a black box for layer N + 1 Design a flat interface that offers Design a flat interface that offers
layer N’s serviceslayer N’s services This can be achieved by the Façade This can be achieved by the Façade
patternpattern Necessitates introduction of a Necessitates introduction of a
Façade objectFaçade object
What is a Black Box?What is a Black Box?
13
Ob
ject
-Ori
en
ted D
esi
gn
Consequences of Black Box Consequences of Black Box ApproachApproach
Supports system evolutionSupports system evolution Can support multiple interface Can support multiple interface
implementations (see Bridge implementations (see Bridge pattern)pattern)
May not be the most efficient May not be the most efficient approachapproach
Adds to project time Adds to project time
14
Ob
ject
-Ori
en
ted D
esi
gn
What is a White Box?What is a White Box?
Layer N + 1 sees internals of layer NLayer N + 1 sees internals of layer N Upper layer may access modules in Upper layer may access modules in
layer Nlayer N Introduces explicit couplingIntroduces explicit coupling Compromise: ‘gray’ boxCompromise: ‘gray’ box
15
Ob
ject
-Ori
en
ted D
esi
gn
What is a Gray Box?What is a Gray Box?
Something between White and Something between White and Black!Black!
Layer N + 1 knows number of Layer N + 1 knows number of components in layer Ncomponents in layer N
Each component is addressed Each component is addressed separatelyseparately
However, it does not know about However, it does not know about component internalscomponent internals
16
Ob
ject
-Ori
en
ted D
esi
gn
Consequences of White Box Consequences of White Box Approach Approach
Relatively easy to implementRelatively easy to implement Incremental developmentIncremental development Large maintenance costsLarge maintenance costs Low reusability levelsLow reusability levels
17
Ob
ject
-Ori
en
ted D
esi
gn
Levels of Information HidingLevels of Information Hiding
Black Box White Box Gray Box
18
Ob
ject
-Ori
en
ted D
esi
gn
Layers: Steps Part ILayers: Steps Part I
1:1: Determine abstraction criteria Determine abstraction criteria for task for task grouping grouping
2:2: Determine the number of Determine the number of abstraction abstraction levelslevels
3:3: Name layers and assign tasks to Name layers and assign tasks to themthem
4:4: Specify layers’ servicesSpecify layers’ services 5:5: Refine the layeringRefine the layering
19
Ob
ject
-Ori
en
ted D
esi
gn
Abstraction CriteriaAbstraction Criteria
Most difficult step during layering Most difficult step during layering processprocess
Determine the different tasksDetermine the different tasks Then groups tasks into layersThen groups tasks into layers Iterative processIterative process OOA use cases are of help hereOOA use cases are of help here
20
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
PAC ModelPAC Model
Three layers and three major tasksThree layers and three major tasks Task 1Task 1: Interactions with external : Interactions with external
environmentenvironment Task 2Task 2: Business objects and logic : Business objects and logic
managementmanagement Task 3Task 3: Communication with other : Communication with other
agentsagents
21
Ob
ject
-Ori
en
ted D
esi
gn
Number of Abstraction Number of Abstraction LevelsLevels
Each abstraction level corresponds Each abstraction level corresponds to 1 layerto 1 layer
Can split a layer into 2 layersCan split a layer into 2 layers Layers can be combinedLayers can be combined Associated advantages and Associated advantages and
disadvantagesdisadvantages
22
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
PACPAC
Three layers (P, A, C)Three layers (P, A, C) Correspond to UML (B,E,C) patternCorrespond to UML (B,E,C) pattern Sufficient regime for many Sufficient regime for many
applicationsapplications In some cases we can split A into 2 In some cases we can split A into 2
layerslayers Then get a 4-layer regimeThen get a 4-layer regime
23
Ob
ject
-Ori
en
ted D
esi
gn
LayersLayersNames and ResponsibilitiesNames and Responsibilities
Highest layer is overall system taskHighest layer is overall system task Other tasks are ‘helpers’Other tasks are ‘helpers’ Lower layers provide an Lower layers provide an
‘infrastructure’‘infrastructure’ Higher layers use services of lower Higher layers use services of lower
layerslayers Demands experience and foresightDemands experience and foresight
24
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
PACPAC
Layer 1Layer 1: SensorUnit (interaction with : SensorUnit (interaction with environment)environment)
Layer 2Layer 2: ModelledEntity (objects of : ModelledEntity (objects of interest)interest)
Layer 3Layer 3: Controller : Controller (dispatching/notification)(dispatching/notification)
25
Ob
ject
-Ori
en
ted D
esi
gn
Services of LayersServices of Layers
High-level description of what a layer High-level description of what a layer offers to upper layersoffers to upper layers
Keep services distinctKeep services distinct Locate more services in higher layersLocate more services in higher layers This reduces programmer ‘cognitive This reduces programmer ‘cognitive
overload’overload’
26
Ob
ject
-Ori
en
ted D
esi
gn
Layer RefinementLayer Refinement
Iterate over steps 1 to 4Iterate over steps 1 to 4 Combination of top-down and Combination of top-down and
bottom-up approachesbottom-up approaches Be careful not to destroy strict Be careful not to destroy strict
layeringlayering
27
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
Moving from PAC to Agent Moving from PAC to Agent TechnologyTechnology
Agent technology uses a number of Agent technology uses a number of layered modelslayered models
Can be seen as an extension of the Can be seen as an extension of the OO modelOO model
A 4-layer regime is commonA 4-layer regime is common
28
Ob
ject
-Ori
en
ted D
esi
gn
Prototypical 4-layer ModelPrototypical 4-layer Model
Level 1:Level 1: World interface layer World interface layer (sensors)(sensors)
Level 2:Level 2: Behavioural layer (reactive Behavioural layer (reactive objects)objects)
Level 3:Level 3: Planning layer (algorithms, Planning layer (algorithms, proactive proactive objects)objects)
Level 4:Level 4: Communication layer (group Communication layer (group planning, communication planning, communication
with other with other agents)agents)
29
Ob
ject
-Ori
en
ted D
esi
gn
Layers: Steps Part IILayers: Steps Part II
6: Specify an interface for each layer6: Specify an interface for each layer 7: Structure individual layers7: Structure individual layers 8: Specify communication between 8: Specify communication between
layerslayers 9: Decouple adjacent layers9: Decouple adjacent layers 10: Design an error-handling 10: Design an error-handling
strategystrategy
30
Ob
ject
-Ori
en
ted D
esi
gn
Layer InterfacesLayer Interfaces
Problem of finding interfaces for Problem of finding interfaces for each layereach layer
Differences for white, black and gray Differences for white, black and gray boxesboxes
Sequence diagrams help hereSequence diagrams help here Possible to define and discover Possible to define and discover
standard interfacesstandard interfaces
31
Ob
ject
-Ori
en
ted D
esi
gn
Layer StructureLayer Structure
Objective is to structure the internals Objective is to structure the internals of each layerof each layer
Break a layer into finer componentsBreak a layer into finer components Gamma patterns are useful at this Gamma patterns are useful at this
levellevel Finer-grained structuresFiner-grained structures
32
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
PACPAC
BridgeBridge: support multiple : support multiple implementations of a layer interfaceimplementations of a layer interface
CompositeComposite: complex aggregate : complex aggregate objectsobjects
StrategyStrategy: dynamic interchange of : dynamic interchange of algorithms in a layeralgorithms in a layer
StateState: implementing state machines : implementing state machines in an objectin an object
33
Ob
ject
-Ori
en
ted D
esi
gn
Using Bridges in LayersUsing Bridges in Layers
L3 Object
L2 Object
3
2 Imp
D1 D2 . . .
{abstract}
34
Ob
ject
-Ori
en
ted D
esi
gn
Inter-layer CommunicationInter-layer Communication
Determines how layers exchange Determines how layers exchange informationinformation
Precondition is that they ‘know’ each Precondition is that they ‘know’ each other in some wayother in some way
Choice depends on a number of Choice depends on a number of factorsfactors
35
Ob
ject
-Ori
en
ted D
esi
gn
Determining the best ChoiceDetermining the best Choice
Loose coupling (callbacks, implicit Loose coupling (callbacks, implicit invocation)invocation)
Efficiency (peer-to-peer model)Efficiency (peer-to-peer model) Ability to switch at configuration Ability to switch at configuration
time or run-timetime or run-time
36
Ob
ject
-Ori
en
ted D
esi
gn
Decouple adjacent LayersDecouple adjacent Layers
Optimisation step, many optionsOptimisation step, many options Two-way or one-way couplingTwo-way or one-way coupling Callbacks help one-way couplingCallbacks help one-way coupling Use of C++ abstract classesUse of C++ abstract classes Use of Bridge patternUse of Bridge pattern
37
Ob
ject
-Ori
en
ted D
esi
gn
Error-handling StrategyError-handling Strategy
Really a separate design/analysis Really a separate design/analysis issueissue
Has a major performance impact on Has a major performance impact on layered systemslayered systems
Handle error in current layer or hand Handle error in current layer or hand it off to next layer?it off to next layer?
Rule: handle errors at lowest Rule: handle errors at lowest possible layerpossible layer
38
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
PACPAC
P: hardware errors (no response, P: hardware errors (no response, heavy response)heavy response)
A: emergency requestsA: emergency requests C: notification errorsC: notification errors
39
Ob
ject
-Ori
en
ted D
esi
gn
Advantages of LayeringAdvantages of Layering
Reuse of layersReuse of layers Support for standardisationSupport for standardisation Dependencies are kept localDependencies are kept local Exchangeability of layers (via Bridge)Exchangeability of layers (via Bridge)
40
Ob
ject
-Ori
en
ted D
esi
gn
Disadvantages of LayeringDisadvantages of Layering
Cascades of changing behaviourCascades of changing behaviour Lower efficiencyLower efficiency Unnecessary workUnnecessary work Correct granularity of layers. What is Correct granularity of layers. What is
it?it?
41
Ob
ject
-Ori
en
ted D
esi
gn
Layering and PAC: last Layering and PAC: last RemarksRemarks
Similarities (levels of increasing Similarities (levels of increasing abstraction)abstraction)
PAC structure is a tree of PAC nodesPAC structure is a tree of PAC nodes Layers is a vertical line of nodesLayers is a vertical line of nodes Each PAC node consists of three Each PAC node consists of three
componentscomponents Layers does not prescribe how many Layers does not prescribe how many
layers to createlayers to create
42
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
Steam-Boiler ProblemSteam-Boiler Problem
Well-known prototype problemWell-known prototype problem Objective here is to show how layers Objective here is to show how layers
are implementedare implemented Knowing what was done allows us to Knowing what was done allows us to
improve the code quality and improve the code quality and flexibilityflexibility
Three layers in general (based on Three layers in general (based on PAC)PAC)
We concentrate on Delivery agentWe concentrate on Delivery agent
43
Ob
ject
-Ori
en
ted D
esi
gn
DeliveryDelivery
Responsible for producing heat and Responsible for producing heat and coldcold
Realised by physical actuatorsRealised by physical actuators Knows about provision of servicesKnows about provision of services 3-layer agent3-layer agent
44
Ob
ject
-Ori
en
ted D
esi
gn
Abstraction CriteriaAbstraction Criteria
Desire to distance system from Desire to distance system from physical hardwarephysical hardware
Locate interactions with hardware in Locate interactions with hardware in one layerone layer
Another layer knows what service is Another layer knows what service is needed and what it can provideneeded and what it can provide
Upper layer is responsible for Upper layer is responsible for communi-cating results and communi-cating results and acknowledgementsacknowledgements
45
Ob
ject
-Ori
en
ted D
esi
gn
Layer Names and TasksLayer Names and Tasks
DeliveryDelivery: 2-way : 2-way dispatching/notificationdispatching/notification
ActuatorUnitActuatorUnit: current service needs : current service needs and resourcesand resources
ActuatorsActuators: Physical heating/cooling : Physical heating/cooling unitsunits
Names can be generalised (later)Names can be generalised (later)
46
Ob
ject
-Ori
en
ted D
esi
gn
ServicesServices
Each layer provides services to Each layer provides services to upper layerupper layer
Define service-access points (SAPs) Define service-access points (SAPs) and service provision points (SPPs)and service provision points (SPPs)
SAP and SPP are closely relatedSAP and SPP are closely related SAP is ‘upper’ part, SPP is ‘lower’ SAP is ‘upper’ part, SPP is ‘lower’
partpart SAP and SPP ensure that layers are SAP and SPP ensure that layers are
uncoupleduncoupled
47
Ob
ject
-Ori
en
ted D
esi
gn
ServicesServices
ActuatorControlActuatorControl: heat and cold : heat and cold regulation levelsregulation levels
ActuatorsActuators: heat and cold regulation: heat and cold regulation DeliveryDelivery: service requests: service requests No layer refinementNo layer refinement
48
Ob
ject
-Ori
en
ted D
esi
gn
Interfaces for LayersInterfaces for Layers
C++ usedC++ used Interface functions based on Interface functions based on
sequence diagramssequence diagrams White box approachWhite box approach Tight coupling between layers (call Tight coupling between layers (call
and return mechanism)and return mechanism)
49
Ob
ject
-Ori
en
ted D
esi
gn
Inter-layer communicationInter-layer communication
Realised by function callsRealised by function calls Layers know address of upper and Layers know address of upper and
lower neighbourslower neighbours Return and call: all action starts in Return and call: all action starts in
MediatorMediator We can call it a pull modelWe can call it a pull model
50
Ob
ject
-Ori
en
ted D
esi
gn
Decoupling LayersDecoupling Layers
Not done in this version of the Not done in this version of the softwaresoftware
Use of C++ inheritance and Event Use of C++ inheritance and Event classes enhances loose couplingclasses enhances loose coupling
use Command pattern to pass use Command pattern to pass functions from layer to layerfunctions from layer to layer
51
Ob
ject
-Ori
en
ted D
esi
gn
Error HandlingError Handling
All events (including errors) are All events (including errors) are modelled by Event classesmodelled by Event classes
Specialised events per agentSpecialised events per agent All handling takes place in MediatorAll handling takes place in Mediator Centralised control (more Centralised control (more
dependencies)dependencies)
52
Ob
ject
-Ori
en
ted D
esi
gn
ExampleExample
Financial Services Financial Services ArchitectureArchitecture
Provides access to financial services Provides access to financial services from an applicationfrom an application
Ability to communicate with various Ability to communicate with various service providersservice providers
Precondition: no code changePrecondition: no code change
53
Ob
ject
-Ori
en
ted D
esi
gn
ArchitectureArchitecture
3 main layers3 main layers XFS APIXFS API: used by application: used by application XFS SPIXFS SPI: interfaces to specific service : interfaces to specific service
providersproviders XFS ManagerXFS Manager: maps API calls to : maps API calls to
appropriate service providerappropriate service provider
54
Ob
ject
-Ori
en
ted D
esi
gn
XFS ArchitectureXFS Architecture
XFS APIs
XFS Manager
XFS SPIs
User
Configuration Information
. .
Service Providers
55
Ob
ject
-Ori
en
ted D
esi
gn
Remarks on CommunicationRemarks on Communication
API calls can be synchronous or API calls can be synchronous or asynchronousasynchronous
SPI calls are always asynchronousSPI calls are always asynchronous Service provider entry point is Service provider entry point is
always localalways local Device or service (final target) may Device or service (final target) may
be remotebe remote
56
Ob
ject
-Ori
en
ted D
esi
gn
Responsibilities of Service Responsibilities of Service ProvidersProviders
Translate generic service requests to Translate generic service requests to service-specific requestsservice-specific requests
Request routingRequest routing Arbitrate access by multiple apps to Arbitrate access by multiple apps to
a single service or devicea single service or device Manage hardware interfaces to Manage hardware interfaces to
services or devicesservices or devices Manage asynchronous nature of Manage asynchronous nature of
services and devicesservices and devices
57
Ob
ject
-Ori
en
ted D
esi
gn
API FunctionsAPI Functions
Basic: StartUp/CleanUp, Open/Close, Basic: StartUp/CleanUp, Open/Close, Lock/UnlockLock/Unlock
Administration functions (e.g. device Administration functions (e.g. device init)init)
Specific commands (e.g. request Specific commands (e.g. request device/service-specific functions)device/service-specific functions)
SPI functions kept as close as SPI functions kept as close as possible to API functionspossible to API functions