You are on page 1of 70

Block III: From architecture to product

Unit 9: Architecture, patterns and reuse

1
 The unit explores the two main concepts of structure and
reuse.

 You will learn about software architecture and how it relates


to the requirements for a system.

 You will also explore different reuse mechanisms for


architectures and design, such as styles and patterns, that
build upon experience gained by software engineers in the
past.

Note that: All SAQs and Exercises in this unit are required.

2
Section 1: Introduction

 This unit looks at two central principles of all engineering disciplines:


structure and reuse.

 First we look at software architecture, which is concerned with software


elements, their externally visible properties (in other words their
interfaces in the widest sense) and their relationships (which include their
interactions).

 We then examine how architecture interacts with requirements and we


shall see that architecture and requirements evolve together and are
closely intertwined.

 We look at how different views can be used to represent the system –


focusing on the logical, process and deployment views – and how models
and conventions are used to describe these views.

3
Section 1: Introduction

 An important goal of software engineering is reuse.


 We look at architectural styles, which represent basic forms of
architecture we can reuse in the design of new systems.
 Frameworks and product lines provide complete architectures designed
for reuse.
 Architecture is only one part of the design of a software system.
 The other part of the design is the internal structure of the software
elements themselves.
 Software patterns represent reusable solutions to common design
problems at this level.
 We discuss a number of important patterns and give examples of their
use.

4
Section 2 : Architecture

What is software architecture?

 In this section we look at software architecture and how it interacts with


 requirements.

 In Block 1 Unit 1 software architecture was defined as follows.

◦ The software architecture of a program or computing system is the


structure or structures of the system, which comprise software
elements, the externally visible properties of those elements, and the
relationships among them.

 A popular architecture for websites is the LAMP stack.

5
Section 2 : Architecture

 The acronym LAMP refers to the use of four open-source technologies:


◦ Linux
◦ Apache webserver
◦ MySQL database
◦ PHP (or Python or Perl – all programming languages).
 The structure is shown in Figure 2.

Figure 2 LAMP stack


 Variants on this architecture may replace Linux with other operating systems, for
example Microsoft Windows (a WAMP) or Mac OS (a MAMP).

6
Section 2 : Architecture
 Figure 3 shows the very different architecture used by Skype, a well-known
internet telephony service.

 Skype’s software is all proprietary. Skype users


must download and use the software Skype
provides and cannot use alternative software
from third parties.
 Originally all the nodes except the login server
were equivalent to one another. Any suitable
node could be promoted to a super node and
become responsible for routing calls.
 This style of architecture, in which there is no
clear distinction between clients and servers, is
known as peer-to-peer (P2P).
 Subsequently it was decided to move the super
nodes to Skype’s own servers in order to
improve reliability. Figure 3 Skype architecture
 Skype now has a mixed P2P and client–server
architecture

7
Section 2 : Architecture

 Figure 5 is an example of a particular form of architecture called pipe-


and-filter or data flow, which we will meet again in Section 4.

 You may also find references to pipe-and-filter as design or architectural


pattern – we will be discussing patterns in Section 5 but the distinction
between an architecture and a pattern is not always clear.

Figure 5 Pipes and filters

8
Section 2 : Architecture

The twin peaks of architecture and requirements


 Figure 6 shows a twin-peaks model (Nuseibeh, 2001), which develops
requirements and architecture concurrently and iteratively

 The twin-peaks model gives


equal prominence to
requirements and architecture
and uses an extension of the
spiral process you met in Block 1
Unit 1.

 As you descend the peaks you


consider alternately requirements
and architecture, intertwining the
two and with each successive
iteration specifying both in greater Figure 6 Twin-peaks model (adapted from
detail. Nuseibeh, 2001)

9
Section 2 : Architecture

Can architecture and agile live together?

 A lot of attention has rightly been given to the question of whether there is a
conflict between architecture and agility.
◦ An architecturally focused approach will start to consider very early on
what the main elements of the system are and how they will interact.
◦ An agile approach will typically emphasise being adaptive and delaying
decisions for as long as possible.

 Some agile practitioners may:


◦ take the view that there is no need to pay any special attention to architecture, as it will
emerge naturally as a result of addressing requirements in a series of iterated code
development cycles.
◦ prefer to avoid explicit architectural decisions in case they limit the flexibility of developers
to respond to changes in user requirements.
◦ also fear that architecture is associated with ‘big design up front’ (BDUF), which limits
flexibility and runs against the lightweight development ethos of agile.

 10
Section 2 : Architecture

 Architecture and agility are far from incompatible and in fact can benefit
one another.
 By giving architecture equal emphasis with requirements, twin-peaks model
helps to answer the criticism often made that agile does not scale up to
larger projects.
 The interweaving of requirements and architecture allows customers to
become involved in architectural decisions.
 In a recent survey,Falessi et al. (2010) found that many agile practitioners
consider architecture to be important for complex projects and that agile
values and architecture are mutually supportive.

 Architecture is seen as contributing in a variety of ways, such as:


◦ aiding communication
◦ documenting assumptions about the system
◦ feeding into subsequent development cycles.

11
Section 2 : Architecture

Requirements and architectural decisions

 There can be multiple architectures that meet the functional requirements but they
will not all be equal when it comes to non-functional requirements.
 Not all non-functional requirements will be of equal importance when making
architectural decisions.
 Figure 7 illustrates that meeting non-functional requirements is a stronger restriction
than meeting functional ones.

Figure 7 Meeting non-functional requirements is more restrictive


12
Section 2 : Architecture
Architecturally significant requirements
 The four characteristics identified by Chen et al. (2012) are as follows:

Characteristics Description Example

Quality Non-functional requirements Security, reliability, availability, usability,


attributes maintainability, portability and so on
Core features Described as ‘the problem the An online chat application is intended to
software is trying to solve’ allow participants in different locations to
exchange text messages. To do this a
network of some sort is essential, which
immediately has implications for the
architecture
Constraints Requirements such as technical The client may have specified a particular
constraints programming language – or non-technical
constraints such as budget or time
Application This is the environment in which A navigation app will need GPS
environment the system will run connectivity

13
Section 2 : Architecture
Architectural views
Architectural views proposed by Kruchten (Kruchten, 2004) Bass et al. (2003) present a slightly different set, although
- a ‘4+1 model’ they are essentially equivalent to Kruchten’s.

The logical (or functional) view describes the The module view corresponds to the logical view in
system’s main functional elements and their the 4+1 model.
interactions – broadly, the services the system must
provide to users.
The process view describes the set of independently The component and connector view is similar to the
executing processes that will exist at run-time and the process view in the 4 +1 model, with the independent
communication between them. processes being regarded as components and the
communications between them modelled by
connectors.
The physical (or deployment) view describes how the
system will be deployed to an operating environment in The allocation view describes all the mappings
terms of the physical computers and networks on which between the software and the external environment in
the system will run. the widest sense and roughly corresponds to a
combination of the physical and development view in
The development view describes how the software the 4+1 model.
will be split into subsystems that can be allocated to
teams of developers.

14
Section 2 : Architecture

TM354 view set comprises the following:

The logical view Describes the main functional elements and how they interact,
and assumes that these correspond to subsystems that can be
allocated to teams of developers
The process view Describes the independent processes executing at runtime and
the communication between them, regarding the processes as
components and the communication as taking place via
connectors

The deployment view Describing how the system will be deployed to an operating
environment, the physical computers and networks on which
the system will run.

15
Section 2 : Architecture

Stakeholders, views and viewpoints


stakeholders A system will have many groups of stakeholders and each stakeholder
group will have a particular set of concerns.
A concern is some aspect of the system that is of crucial importance from
the point of view of one or more groups of stakeholders.

Views The views should be intelligible to stakeholders and should allow them to
see how the architecture deals with their concerns and how the architect
has balanced the claims of competing concerns by suitable
compromises.

viewpoint In software architecture the set of conventions and models appropriate to


a particular view is often referred to as a viewpoint.

16
16
Section 2 : Architecture

 A conceptual framework for architectural descriptions, a simplified version


is shown in the UML diagram of Figure 8.
 Note the aggregation diamonds, which express the fact that the
architectural description consists of a set of views and viewpoints.

Figure 8 Conceptual framework for architectural descriptions

17
17
Section 2 : Architecture
Summary of section
 In this section you first revisited the definition of a software architecture and then saw
several examples of different architectures.
 Requirements and architecture go hand in hand and both must be considered in parallel
right from the start. Following an iterative twin-peaks model of development allows
architecture to be responsive to change and to provide support for agile development in
ways such as aiding communication, documenting assumptions and contributing to
subsequent iterations.
 Non-functional requirements shape architecture, along with other considerations such
as the system’s core purpose and the environment it will run in. Collectively these
factors are known as architecturally significant requirements (ASRs).
 An architectural view is a representation of the system that emphasises the concerns of
a particular set of stakeholder groups. The description of an architecture requires
several such views because no one view can capture the concerns of all the
stakeholders.
 A range of view sets have been proposed. The version used in this module consists of
the logical, process and deployment views.
 Each architectural view has a particular set of models and conventions that are used to
describe it. This is often called a viewpoint.

18
A major aspiration of software engineering is reuse – taking what you or others have
done or created in the past and using it either unchanged or with relatively little
adaptation.

Reasons why reuse is desirable:

 It avoids duplication of effort and reinventing already existing solutions, which


saves resources.
 It promotes reliability because developers can use tried and trusted solutions.
 It speeds up development because developers can take existing solutions without
starting from the beginning every time.
 It is a mechanism for spreading good practice among the software development
community and familiarizing practitioners with tried and tested solutions.

19
Section 3: Reuse

Reuse on different levels


Software Replaceable and reusable software elements
components
Requirements Knowledge in the elicitation of requirements
patterns

Analysis patterns Ways of solving conceptual analysis problems

Architecture Reusing a structural idea or the creation of a series of systems


by taking the same basic architecture and modifying the detailed
code

Design patterns Ways of solving particular problems of design and


implementation
Idioms Small units of reuse-ways of doing things in in a particular
language

20
Section 3: Reuse

Summary of section

 In this short section you saw that as well as reusing software


components an important aspect of software engineering is the reuse of
ideas and patterns that have proved successful in the past.

 This can take place on a range of levels, from architecture down to ways
of doing things in a particular language, and at different stages, from
requirements through to analysis and design.

21
Section 4: Reusing architecture

Architectural styles

 At a very general level we can identify a number of basic plans used in


software architecture; these have come to be known as architectural
styles
 Commonly architectural styles include:
1. Client–server
2. Call-return
3. Layered
4. Peer-to-peer
5. Data flow
6. Data-centred
7. Independent components
8. Service-oriented
9. Notification

22
Section 4: Reusing architecture

1. Client–server

 Client–server style is probably the best


known of all architectural styles.

 One component (the server) provides


a service to the other component
(the client). The server waits for
requests from clients, processes each
one as it as received, and returns a
response to the client.

 A familiar example of the client–server


style is a request sent from a web
Figure 9 Client–server architectural style
browser to a web server. The client–
server style is illustrated in Figure 9.

23
Section 4: Reusing architecture

2. Call-return

 In a call-return style a component


(the caller) makes a procedure call
to another component (often
known as the callee) and waits for
the call to return.
 In traditional software a main
program calls a subprogram and then
waits for a reply. In object-oriented
programming the call takes the form
of a method invocation by one object Figure 10 Call-return architectural style
on another by the sending of a
message.
 The call-return style is illustrated in
Figure 10.

24
Section 4: Reusing architecture

3. Layered Examples:
 A compiled Java program, which
 The essence of a layered style is executes in a Java virtual machine
that the system is structured as a that in turn makes calls to services
series of layers that are supplied by the operating system.
visualised as stacked on top of
another.
 A client–server architecture, in
 Each layer uses services provided
which there are just the two layers
by the layers below (usually just by and the connector takes the form of
the layer immediately below). It also a request and response, often over
supplies services to the layer a network.
above.

25
Section 4: Reusing architecture

 The components in this style


are the various services in
each layer and the connectors
are the calls made on the
services.
 Normally a layer can only
communicate with layers
above and below. There is no
communication between
components in the same
layer.
Figure 11 Layered architectural style
 The layered style is illustrated
in Figure 11.

26
Section 4: Reusing architecture
4. Peer-to-peer

 The peer-to-peer style resembles the


client–server style except that all the
components are both clients and
servers and any component can
request services from any other
component.

 Example
◦ Streaming music service, where listeners
generally get streamed tracks from the nearest
peer that can be located by sending a request that
hops from one peer to another until the desired
track is located.
 The peer-to-peer style is illustrated in Figure 12 Peer-to-peer architectural style
Figure 12.

27
Section 4: Reusing architecture
5. Data flow (also known as pipes and filters)
 The data-flow style components are objects or small independent subprograms
(filters) that process a stream of data and pass the results on to other
components for further processing.
 Communication is unidirectional and uses fixed channels. Each filter has no
knowledge of other filters upstream or downstream, but simply accepts the data,
processes it and passes it on.
 The connectors are services, provided by the operating environment, that ‘pipe’
data from one filter to another.
◦ This type of architecture is commonly used in the Unix operating system for combining
functions and is also seen in the Stream application programming interface (API)
introduced from Java 8 onwards.
 The data-flow style is illustrated in Figure 13.

Figure 13 Data-flow architectural style


28
Section 4: Reusing architecture
6. Data-centred
 In the data-centred style there is a data provider that is a centralised store of
persistent data.
 The structure of the data, the types of items and their relationships are stable and
change rarely or not at all.
 There are many clients who are data consumers. Items can be created, queried,
updated and destroyed on request.
 The central store may be duplicated, to provide backup in case of failure or to deal
with a greater volume of client requests.
 The communication channels are normally fixed.

 There are two forms of the data-centred style (see Figures 14(a) and (b)):
◦ If communication is always initiated by clients and the store simply responds to requests it is called
database or repository. Typically the components are a database server and clients that access it. The
connectors are database queries made via a special database connection. A database holding
personnel records is an example of this form, with authorised users being able to log on and submit
queries.
◦ A variant in which the store is active and informs users of changes, so that communication may be
initiated from either end, is termed a blackboard.

29
Section 4: Reusing architecture

 There are two forms of the data-centred style (see Figures 14(a) and (b)):
◦ If communication is always initiated by clients and the store simply responds to requests it
is called database or repository. Typically the components are a database server and
clients that access it. The connectors are database queries made via a special database
connection. A database holding personnel records is an example of this form, with
authorised users being able to log on and submit queries.
◦ A variant in which the store is active and informs users of changes, so that communication
may be initiated from either end, is termed a blackboard.

Figure 14 Data-centred architectural style, (a) database, (b) blackboard

30
Section 4: Reusing architecture

7. Independent components

 In the independent components style,


components execute concurrently and are
decoupled as far as possible, but can
communicate by messages that allow them
to exchange data or coordinate their
operations.
 The connectors are the message exchange
protocols, which are normally asynchronous
– that is, the sender can continue without
waiting for an answer from the other
component.
◦ For example, a set of components might control Figure 15 Independent components architectural style
different parts of a chemical processing plant,
independently regulating the part each is responsible
for, but sharing data and coordinating with one another
by exchanging messages.
 Figure 15 illustrates an example of the
independent components style.

31
Section 4: Reusing architecture

8. Service-oriented

 In the service-oriented style there are two kinds of component, the


consumers and the providers – a set of service providers makes
services available to a set of service consumers.
 Consumers can combine services in order to carry out the business
processes they require.
 The connectors are the requests and responses sent between consumers
and providers, using standard communication protocols.
 In some cases communication is facilitated by a virtual communication
channel called an enterprise service bus (ESB), which supports features
such as service look-up and routing of service requests.
◦ Example:
 Different divisions of an organisation whose systems all use a common set of services
such as payroll, personnel, customer records management billing and so on.

32
Section 4: Reusing architecture

Figure 16 illustrates a service-oriented style using an ESB.

Figure 16 Service-oriented architectural style with ESB

33
Section 4: Reusing architecture
9. Notification
(also known as implicit invocation or publish– subscribe)

 In the notification style the two kinds of components are observers and
subjects.
 Observers can register themselves with a subject in order to be kept
notified whenever some particular event happens at the subject’s end.
 At an architectural level this style is usually referred to as publish–
subscribe.
 Subscribers register to receive updates (often messages) whenever a
publisher posts a new item.
◦ Examples:
 An RSS feed where anyone who signs up to the feed receives news updates as they become
available. Notification also appears at a more detailed design level.
 An event-based model such as Java Swing, in which components can register themselves with other
components to receive information about events such as user input and react to them by executing
appropriate event-handling code.

34
Section 4: Reusing architecture

 In publish–subscribe there
tend to be many subscribers
for each publisher.
 The connectors are either
procedure calls or
messages transmitted via
intermediate software such
as a messaging system or a
run-time system like the
Java virtual machine. Figure 17 Publish–subscribe architectural style

 Figure 17 illustrates the


publish–subscribe form of
the notification style.

35
Section 4: Reusing architecture
Reuse of Frameworks and Product Lines

Frameworks Product Lines


 It may be possible to reuse a large part of  Reuse reference architectures, software
the architecture, along with any code the components and expertise about the
systems have in common. Segments of variations needed to fulfil customer
architecture and code that can be reused requirements.
in this way are usually called frameworks.
 The framework is accompanied by ◦ For example, engines in motor cars are
documentation giving the details of how it controlled by an on-board computer that
is used. uses quite sophisticated software. Different
◦ An example is the Java Swing engines and cars require slightly different
framework for constructing graphical engine-control software, but all engine
user interfaces. To define the graphical controllers are essentially the same.
components of the interface –
windows, menus, buttons and so on –  A manufacturer of engine-control software can
the developer extends classes that produce a series of engine controllers for
form part of the framework. different customers, reusing major parts of the
software from customer to customer, with only
those parts peculiar to the particular customer
being different.

36
Section 4: Reusing architecture

The product-line process

 A software product line is essentially a domain-specific framework.


Building and using a software product line follows a series of stages.

1. Product-line initiation For each particular product a further


2. Domain analysis four stages are needed.
3. Architecture specification
4. Component collection 5. Specific-requirements capture.
6. Architecture specialisation
7. Component selection and
specialisation:
8. Integration and release:

37
Section 4: Reusing architecture
Summary of section

 In this section you were introduced to a range of common architectural styles –


basic plans that an architecture can follow. Styles are characterised in terms of the
types of component involved and the forms of communication between them.
 They can be combined to give more complex architectures and most systems
involve the use of more than one style.
 A framework consists of some architecture, code for software components that slot
into the architecture and the documentation needed to use the framework.
 By adapting the components as appropriate it is possible to develop many
different systems that reuse the basic architecture and code the framework
provides.
 A company will often want to produce a range of very similar software systems.
 It is often possible to create a domain-specific framework called a software
product line, which reuses not only architecture and code but also expertise about
how to fulfil the requirements of different customers.

38
Section 5: Reusing design

Adapter design pattern

 The adapter design pattern which sits


between the device and the supply (see
Figure 18). The adapter plugs into the
local supply and the device plugs into
the adapter.
Figure 18 Adapter

Figure 19 shows an initial class diagram for the adapter pattern

Figure 19 Initial design

39
Section 5: Reusing design

 Where Square has the operation draw() the RoundedSquare class has render()

 The solution is to introduce an Adapter class, which extends Square but has a
RoundedSquare attribute, shown as rs : RoundedSquare in Figure 22.

Figure 22 Adapter
40
Section 5: Reusing design

 When the Adapter receives a draw() message it simply forwards a render()


message to the RoundedSquare and the latter produces the required shape (see
Figure 23).

Figure 23 Forwarded message

41
Section 5: Reusing design

Adapter Pattern- Features

 the Adapter is transparent to the


1. The pattern uses inheritance – an
other classes – neither the Client
Adapter is a Square
nor RoundedSquare is aware of its
existence.
 The pattern uses composition (here
simply represented by an association)
 There are many variations on the
– an Adapter has a RoundedSquare
Adapter pattern.
as an attribute.
◦ For example, arguments and
return values will usually be
 These two mechanisms are involved and the adapter may
fundamental to design patterns and need to convert to and from
many patterns exploit both, as the different data formats.
Adapter pattern does.

42
Section 5: Reusing design
Interfaces

 The Adapter pattern is concerned with converting between interfaces


◦ The class model in Figure 22 doesn’t really reflect that.
 The client still thinks it’s dealing with a square but any coupling with a
specific class is something it would be desirable to get away from.
 It would be far better to pull out the operations the client is expecting to
use and show them as an interface.
◦ The UML notation for an interface is shown in Figure 24.
◦ An interface is indicated by using the UML stereotype «interface».
 An interface is not a class and doesn’t define any implementation for its
operations, only their signatures
◦ in other words the operation name, the types of any arguments and the
type of the return value if there is one.

43
Section 5: Reusing design

 The actual implementation of the


operations is defined within classes
that realise the interface.

 A class realises an interface by


defining operations corresponding
to those of the interface, or by
inheriting them from another class.

 A class can realise multiple


interfaces, in which case the class Figure 24 UML notation for an interface
has to declare all the operations found
in all the interfaces, although it may
also have additional operations.

44
Section 5: Reusing design

 The UML notation for realisation


of an interface is shown in
Figure 25.

 The relationship is indicated by


an arrow similar to the one used
to show a generalisation
relationship, but distinguished
by the stem of the arrow being a
dashed line.

Figure 25 Realisation of interface

45
Section 5: Reusing design

Codifying patterns
The most famous example is the catalogue of design pattern
published by the Gang of Four.

 This catalogued 23 design patterns in three categories

◦ Creational patterns, which deal with ways of creating


objects independently of the clients that will use them
◦ Structural patterns, which deal with relationships among
classes and objects
◦ Behavioural patterns, which deal with how objects
communicate and interact.

46
Section 5: Reusing design

We will discuss about five different patterns in this module:


1. Adapter Pattern

2. MVC(Model View Controller)

3. Observer Pattern- which is a behavioural pattern

4. Factory, which is a creational pattern

5. Singleton, another creational pattern often associated with Factory.

We will use a template for documenting design patterns which has the
following entries:
◦ Name
◦ Purpose (also called intent)
◦ What problem does it aim to solve?
◦ How it works – a description of the solution
◦ When to use it
◦ Example of use.

47
Section 5: Reusing design

Adapter Pattern
Name. Adapter.

Purpose Allows a client to use a class that has a different interface from
the one the client is expecting.

How it works An Adapter class is introduced that provides the client with the interface it is
expecting but forwards client requests to an object of the class with the
incompatible interface (the Adaptee). The interface the client is expecting is
called the Target. Figure 26 shows the structure. The UML note explains
that the Adapter implements operation1() by forwarding the message
operation2() to an instance of the class being adapted, the Adaptee.

When to use it. When you want to use a class with a client that is expecting a different
interface from the one the class provides.
Example. Legacy software may need to be integrated with a newer system that uses
a different interface.

48
Section 5: Reusing design

Figure 26 Adapting an interface

49
Section 5: Reusing design
Model-view-controller pattern
Name. Model-view-controller (MVC)
Purpose Splits user interface interaction into three distinct roles: the model of the domain, the
view representing that domain, and the controller of changes to the domain.
How it works It identifies three roles.
• The first is the model, corresponding to an object with some information about the
domain. The model contains data and behaviour and is not directly accessible to the
user. If we consider MVC as a layered architecture the model resides in the application
domain (or business) layer.
• The view is the representation of the model in the user interface: it displays the output
from the system and is what the user perceives of the model’s state. Both the viewer and
the controller reside in the presentation layer, the layer responsible for user dialogue
aspects.
• The controller handles all user inputs that affect the model. The controller also resides in
the presentation layer.
• User inputs to the controller cause changes to the model’s state, which in turn are
reflected in the view (see Figure 29).
• Although the view and the controller are distinct roles, it is important to understand that
they are not always represented by different objects. For example, a tick box shows the
status of some setting, making it part of the view, but it also lets the user change the
setting, making it also part of the controller. ◦ This tight integration is typical of many
frameworks used for building user interfaces. In Java Swing, for example, visual
components are typically used for both input and output.

50
Section 5: Reusing design

Model-view-controller pattern
When to use it When you have a user interface that you want kept separate from the
model. The advantages of this include the following.

• Separation of concerns. When designing a model you focus on


business objects and processes. When designing an interface you are
concerned with user interaction.
• Facilitating testing. User interfaces are notoriously hard to test because
users can perform so many different sequences of actions, and such
testing is usually done manually. Code implementing business logic is
easier to test and tests can be automated. Keeping the model separate
means that you can take advantage of the relative ease of testing.
• Flexibility. Multiple interfaces may be developed for the same model,
allowing the design to cater for different types of users and different
contexts of use.
Example Figure 30 shows an example of a chart (the view) which is a graphical
representation of the state of an underlying model. If the user changes a
value in the table (the controller) the state of the model changes and the
change is propagated to the chart.

51
Section 5: Reusing design

 In the design pattern the component that does the processing – corresponding to
the clockwork (the interlocking gearwheels and so on in a mechanical clock) – is
called the model.
 The part the user sees is called the view.
 A third component is the controller, which corresponds to the controls that are
used to set the clock to the correct time.
 Put together, these three make up the Model-view-controller pattern.

Figure 29 Model-view-controller pattern


52
Section 5: Reusing design
 As a real-life analogue for this, craft suppliers sell clock movements (see Figure 27).

 These are the working parts of a clock but without any clock face or hands. Clock builders
can then add their own clock dial, so a whole range of different clocks can be constructed
that all use an identical design for the clockwork (see Figure 28).

 In the design pattern the component that does the processing – corresponding to the
clockwork (the interlocking gearwheels and so on in a mechanical clock) – is called the
model. The part the user sees is called the view. A third component is the controller, which
corresponds to the controls that are used to set the clock to the correct time. Put together,
these three make up the Model-view-controller pattern.

53
Section 5: Reusing design

Figure 30 MVC structure for data display

54
54
Section 5: Reusing design

 Possible advantages of separating the user interface from the domain


logic.

◦ The user interface is not affected by changes in the implementation of


the business logic.

◦ The same domain logic can be used with different user interfaces.

◦ The business logic can be tested separately from the interface logic.

55
Section 5: Reusing design

Observer Pattern
 Many online forums allow you to subscribe to them and receive an email
notification whenever a new forum post is made. This is an example of the
behavioural design pattern called Observer.
 An observer registers to receive notifications whenever the state of an observable
(usually called the subject) changes (see Figure 31).
 You should be able to see that this pattern is closely related to the notification
architectural style.

Figure 31 Subject and observer

56
Section 5: Reusing design

Observer pattern
Name. Observer (also sometimes known as publish–subscribe like the notification
architectural style which it resembles).
Purpose When partitioning a system into individual classes you want the coupling between
them to be loose so you have the flexibility to vary them independently. But a
mechanism is needed to ensure that when the state of an object changes related
objects are updated to keep them in step.
How it works One object has the role of the subject (or publisher) and one or more other objects the
role of observers (or subscribers). The observers register themselves with the subject
and if the state of the subject changes the observers are notified and can then update
themselves.
There are two extreme variants of this pattern. In the push model the subject sends
the observers detailed information about the change that has occurred. In the pull
model the subject simply notifies the observers that there has been a change and it is
the responsibility of the observers to find out the details they need to update
themselves.
The structure of the pattern is shown in Figure 32. The Subject and the Observer are
interfaces that are implemented by the corresponding concrete classes.
When the state of the subject changes the observer is sent an update() message. The
implementation of the update() operation in the ConcreteObserver is then responsible
for taking appropriate action to update the Observer.

57
Section 5: Reusing design

Observer pattern
When to use it When different parts of a system have to be kept in step
with one another without being too tightly coupled.
Example. As noted, the relationship between the view and the model in an MVC
design can be realised by applying the observer pattern. The view registers
with the model and is notified every time the model’s state changes,
allowing it to update itself to reflect the change.

Figure 32 Observer pattern


58
Section 5: Reusing design

Singleton pattern
 The Singleton pattern is used where there should only be one instance of
a class.
◦ An example would be the strategy of implementing use cases by having all
messages from the user interface sent to a single object that is an instance of a
central class.
◦ Having more than one instance of this class at once might cause problems, for
example they might interfere with one another.
◦ It’s similar to the idea that a company should only have one chief executive.

59
Section 5: Reusing design
Singleton pattern
Name. Singleton.
Purpose In many cases only a single instance of a class is required and allowing
creation of more than one instance would compromise the design of the
system.
How it works • The Singleton class provides no public operation for creating instances.
Instead it defines a public operation getInstance() that lets clients
access the unique instance of the class.
• One way to implement this is shown in Figure 34. The «singleton»
stereotype denotes a Singleton class. Singleton is responsible for
creating its own unique instance and no other class should be able to
create an instance, so the create() operation is private.

Figure 34 Singleton pattern


60
Section 5: Reusing design

Singleton pattern
When to use it. When there must be only one instance of a class. Often this is associated
with some global resource that other classes need access to.
Example. Figure 35 illustrates the application of the singleton pattern to the design of
a media manager in a multimedia application. There should be only one
instance of the manager, which is created by the MediaManager class
itself the first time a client accesses the manager. This strategy of creation
on demand is called lazy instantiation.
• Notice only the operation getManager() is public. The attribute manager
and the operation create() are declared as private, so other classes
have no direct access to them

Figure 35 Media manager example of the Singleton pattern


61
Section 5: Reusing design

Factory pattern

 A factory is a specialised object for creating and initialising objects


needed by clients.

 The name is taken from real-life factories, which are facilities dedicated to
manufacturing products required by their clients.

 In the design pattern the object the factory produces is called the product.

 Some quality requirements that the Factory pattern might help satisfy are
maintainability and portability (and flexibility if it is counted as distinct from
maintainability).

 There are two types of factory patters: Simple factory pattern and Factory
method pattern

62
Section 5: Reusing design

Factory pattern
Name. Factory.
Purpose If the creation and initialisation of an object is complex and liable to
change, making clients responsible for the task introduces an
undesirable level of coupling. Encapsulating the creation in a
dedicated factory class hides the details from the client and reduces
the coupling.
How it works • The structure is shown in Figure 36. The client has a dependency, shown
by a dashed line, on the factory for the creation of the product, and the
factory depends on the Product class to create one of its instances. The
UML stereotype «create» indicates that the dependency between Factory
and Product is at object creation. This expresses the fact that the factory
must know what class to instantiate.
• The factory is often a singleton, as in Figure 36. Having a single instance
and making it available through a system-wide access point makes it
possible for all clients that require the product to use the same factory and
avoid duplicated code.

63
Section 5: Reusing design
Factory pattern
When to use Whenever object creation and initialisation is complex or depends
it. on information that clients may not know or is likely to change.
Example. Many applications need to use a database management system
(DBMS) for storage. A DBMS is an independent program that
applications communicate with using a particular protocol. A
suitable object can handle the communications but needs to be
created and configured correctly for the DBMS concerned. A
connection factory can provide the required object without the client
application needing to know any details.

Figure 36 Factory pattern


64
Section 5: Reusing design

Factory Method pattern

 The Factory Method pattern develops the idea of a factory further and
reduces coupling to the minimum possible.

 A client can use the factory and then the product via interfaces, without
knowing the actual classes of the objects involved.

Factory method pattern


Name. Factory method
Purpose Sometimes a client requires a factory for a product without
knowing the actual class of the product, only its interface.

65
Section 5: Reusing design

Factory method pattern


How it works. • The structure, which is quite complex, is shown in Figure 40.
• The client is not aware of the actual class of the factory or the
product, and interacts with them only via the interfaces. At run
time the appropriate class for the factory will be decided in
some way, for example from a configuration file or from a
system setting, and the concrete factory instantiated. The
factory will then create a product of the required class, without
the client needing to know what that class is.
When to use When the decision about what concrete product to create
it. needs to be deferred.

Example. Consider a framework for document generation, in which


applications can define application-specific documents that can be
manipulated by an editor.
The application of the Factory Method is shown in Figure 41.

66
Section 5: Reusing design

Figure 40 Factory method pattern

67
Section 5: Reusing design

Figure 41 Document factory

68
Section 5: Reusing design

Summary of Section
 In this section you were introduced to design patterns, which are reusable solutions
to problems at a more detailed level.
 You first met the Adapter pattern, which addresses the common problem of an
object having a different interface from the one expected by another object.
 Many catalogues of different patterns have been produced, dealing with different
aspects of software development.
 The most famous example is the catalogue of design pattern published by the
Gang of Four. This catalogued 23 design patterns in three categories: creational,
structural and behavioural.
 You learned about a simplified form of the template the Gang of Four introduced for
describing design patterns and saw it applied to Adapter, which is a structural
pattern.
 Other very common design patterns include the Model-view-controller (MVC)
pattern, the Observer pattern, which is behavioural, and the Singleton and Factory
patterns, which are creational.
 You also learned of some relationships between different design patterns: for
instance in the Factory pattern the factory is often a singleton.

69
Unit Summary

On completion of this unit you should be able to:

 give an example of a software architecture


 explain that requirements and architecture evolve in parallel
 explain that non-functional requirements and other architecturally
significant requirements, not functional requirements, are what drive
architectural decisions
 understand the need for different architectural views and how these relate
to the concerns of different groups of stakeholders
 recognise common architectural styles and understand that most systems
will contain examples of several styles
 understand the concept of a framework and a product line
 appreciate the concept of a software design pattern, talk about design
patterns, and recognise and understand the design patterns studied in the
unit.

70

You might also like