You are on page 1of 78

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) 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. It shows a mixture of architectures:
− a client–server architecture, with the web browser client sending a
request to a web server and receiving a response; and a LAMP stack
platform.
− a layered architecture. There are three layers, corresponding to the
client, the web server that constructs the response and the database
storage.

Figure 2 LAMP stack


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

 The small circles (user 1, user 2, …)


represent individual users.
 To go online a user must first contact a
login server (dotted line from user 1) and is
then connected to the nearest super nodes
(super node 3 in user 1’s case).
 The super nodes then route telephone calls
from one user to another, e.g. user 2 to
user 4 via super nodes 3 and 4.
 It is also possible for two users to be
connected directly (e.g. user 5 and user 6).
 Skype’s software is all proprietary: Skype
Figure 3 Skype architecture
users must download and use the software
Skype provides and cannot use alternative
software from third parties.

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

 Originally all the nodes except the login


server were equivalent. 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.
 Skype now has a mixed P2P and client–
server architecture.
Figure 3 Skype architecture
 This shows an example of how a non-
functional requirement (reliability) can have
a major effect on architecture.

8
Section 2 : Architecture

 Another example on architectures is called pipe-and-filter or data flow, which


we will meet again in Section 4.
 The Windows command-prompt supports some commands that allow us to
process data in a variety of ways, such as:
− findstr/b Find a string at the beginning
− findstr/e Find a string at the end
− sort Sort alphabetically
 These commands are filters: they take some data and process it to produce a
result.
 For example, if elements.txt is a file containing a list of all the chemical
elements then:
findstr/b "P" elements.txt
 will produce a list of all the elements that begin with ‘P’ (Figure 4).

Figure 4 Filter
9
Section 2 : Architecture

 The output from one filter can be ‘piped’ to another filter. The pipe is
visualized as a channel along which the data flows.
 The two filters each perform an independent chunk of processing and are
not aware of one another.
 The Windows command for a pipe is | and the following combination will
pipe the output from findstr/b to findstr/e.
findstr/b "P" elements.txt | findstr/e "um "
 The result of the second filter can be piped to a third sort filter (Figure 5).
findstr/b "P" elements.txt | findstr/e "um" | sort

Figure 5 Pipes and filters

10
Section 2 : Architecture

The twin peaks of architecture and requirements


 We’ve stated that architecture must be considered early in the development
process.
 You learned in Unit 1 that building a view of the system’s architecture in
early iterations is a Unified Process (UP) best practice.
 Figure 6 shows a twin-peaks
model (Nuseibeh, 2001), which
develops requirements and
architecture concurrently and
iteratively.
 The twin-peaks model gives
equal prominence (importance) to
requirements and architecture
and uses an extension of the
spiral process you met in Unit 1.

Figure 6 Twin-peaks model (adapted from


Nuseibeh, 2001)
11
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 emphasize being adaptive and delaying
decisions for as long as possible.

 Some agile practitioners (experts) 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.

 12
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.

13
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


14
Section 2 : Architecture

Architecturally significant requirements

 There are four characteristics that can be used at the requirements


gathering stage to help identify ‘architecturally significant requirements’
(ASRs)
◦ i.e. The requirements that drive a system’s software architecture.
 The four characteristics identified by Chen et al. (2012) are as follows:
1. Quality attributes: are non-functional requirements such as security,
reliability, availability, usability, maintainability, portability and so on.
2. Core features: are described as ‘the problem the software is trying to
solve’.
 For example, an online chat application is intended to 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.

15
Section 2 : Architecture

Architecturally significant requirements

3. Constraints: All requirements can be described as constraints, but here


the authors mean requirements such as technical constraints .
 For example, the client may have specified a particular programming language
or non-technical constraints such as budget or time.
4. Application environment: This is the environment in which the system
will run.
 For example, a navigation app will need GPS connectivity.

16
Section 2 : Architecture
Architectural views

Architectural views proposed by Kruchten (Kruchten, 2004) - a ‘4+1 model’

 The logical (or functional) view describes the system’s main functional elements
and their interactions – broadly, the services the system must provide to users.
 The process view describes the set of independently executing processes that will
exist at run-time and the communication between them.
 The physical (or deployment) view describes how the system will be deployed to
an operating environment in terms of the physical computers and networks on
which the system will run.
 The development view describes how the software will be split into subsystems
that can be allocated to teams of developers.

 The ‘+1’ part of the model is the use of key scenarios – instances of use cases – to
help develop and validate the design.

17
Section 2 : Architecture

 Bass et al. (2003) present a slightly different set, although they are
essentially equivalent to Kruchten’s.

 The module view corresponds to the logical view in the 4+1 model. It
describes the main functional responsibilities of the system and how the
different parts depend on one another.

 The component and connector view is similar to the process view in the
4 +1 model, with the independent processes being regarded as
components and the communications between them modelled by
connectors.

 The allocation view describes all the mappings between the software and
the external environment in the widest sense and roughly corresponds to a
combination of the physical and development view in the 4+1 model.

18
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.
◦ This is effectively an amalgamation of Kruchten’s logical and development views. We made this choice
because we don’t plan to explore in any detail how work is allocated to teams so there is no need for a
separate view.
 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.
◦ This is similar to the process view in the 4+1 model but using the component and connector terminology
borrowed from Bass et al. We made this choice because components and the communication between
them is an important part of the discussions in this unit and the next.
 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.
◦ This is similar to the physical view in the 4+1 model. It is important to us because deployment decisions
will have a major impact on quality attributes.

19
Section 2 : Architecture

Stakeholders, views and viewpoints

 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.
 Concerns can be to do with the system’s functionality or with qualities such as
correctness, performance, security and so on.
 Because an architecture is too complex to be expressed in a single complete
description, we need a number of views, each of which addresses a particular
set of stakeholder concerns.
 The views should be intelligible (clear) to stakeholders and should allow them
to see how the architecture deals with their concerns.
 In software architecture the set of conventions and models appropriate to a
particular view is often referred to as a viewpoint. You can think of a
viewpoint as the language that is used to document a specific type of view.

20
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

21
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.

22
 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.

 Following are some 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 (developers) with tried
and tested solutions.

23
Section 3: Reuse

Reuse on different levels


 Reuse can involve software components – replaceable and reusable
software elements
It can also involve reuse of:
 knowledge in the elicitation of requirements, known as requirements
patterns
 ways of solving conceptual analysis problems, known as analysis
patterns
 architecture – this may just involve reusing a structural idea or it may go
further and allow the creation of a series of systems by taking the same
basic architecture and modifying the detailed code
 ways of solving particular problems of design and implementation, known
as design patterns
 ways of doing things in a particular language – these are small units of
reuse known as idioms.

24
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.

25
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:
◦ Client–server
◦ Call-return
◦ Layered
◦ Peer-to-peer
◦ Data flow
◦ Data-centred
◦ Independent components
◦ Service-oriented
◦ Notification
 It is also important to note that there are relationships between these different
styles and some overlap with others.

26
Section 4: Reusing architecture

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 browser to a web server.
 The client–server style is illustrated in
Figure 9.

Figure 9 Client–server architectural style


27
Section 4: Reusing architecture

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 waits for a reply.

 In object-oriented programming the call takes the form of a method invocation by


one object on another by the sending of a message.
 The call-return style is illustrated in Figure 10.

Figure 10 Call-return architectural style


28
Section 4: Reusing architecture

Layered
 The essence of a layered style is that the system is structured as a series
of layers that are visualised as stacked on top of another.
 Each layer uses services provided by the layers below (usually just by the
layer immediately below). It also supplies services to the layer above.

◦ An example of a layered architecture is a compiled Java program, which


executes in a Java virtual machine that in turn makes calls to services
supplied by the operating system.

◦ Another example is the familiar client–server architecture, in which there


are just the two layers and the connector takes the form of a request
and response, often over a network.

29
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.
 The layered style is illustrated in Figure 11.

Figure 11 Layered architectural style


30
Section 4: Reusing architecture
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.
◦ An example of peer-to-peer is a 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.

Figure 12 Peer-to-peer architectural style

31
Section 4: Reusing architecture
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


32
Section 4: Reusing architecture

Data-centred
 In the data-centred style there is a data provider that is a
centralized 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 (Figures 14):


a. Database or repository.
b. Blackboard.

33
Section 4: Reusing architecture

a. Database: communication is always initiated by clients and the store simply


responds to requests. Typically the components are a database server and
clients that access it. The connectors are database queries made via a special
database connection. Example is a database holding personnel records with
authorized users being able to log on and submit queries.
b. Blackboard: the store is active and informs users of changes, so that
communication may be initiated from either end.

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

34
Section 4: Reusing architecture

Independent components
 In the independent components style (Figure 15), 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 (i.e. the sender can continue without waiting for an answer
from the other component).
 Example: a set of components
controlling 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 Independent components architectural style
35
Section 4: Reusing architecture

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.
◦ An example could be different divisions of an organization whose systems all
use a common set of services such as payroll, personnel, customer records
management billing and so on.

36
Section 4: Reusing architecture

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

Figure 16 Service-oriented architectural style with ESB

37
Section 4: Reusing architecture

Notification (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.
◦ For example 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.
◦ Another example of notification is 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.

38
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 illustrates the publish–subscribe form of the notification style.

Figure 17 Publish–subscribe architectural style


39
Section 4: Reusing architecture

Frameworks
 It may be possible to reuse a large part of the architecture, along with any
code the systems have in common.
 Frameworks: Segments of architecture and code that can be reused.

 The framework is accompanied by documentation giving the details of


how it is used.
◦ An example is the Java Swing framework for constructing graphical user
interfaces. To define the graphical components of the interface – windows,
menus, buttons and so on – the developer extends classes that form part of the
framework.
 Swing uses an event-based model in which event handlers (written by the
developer but based on the software provided by the framework) allow the
interface to respond to user events such as mouse clicks.
 Connections between the graphical components and the event handlers
are created using the facilities of the framework.

40
Section 4: Reusing architecture

Product lines

 Reuse reference architectures, software components and expertise about


the variations needed to fulfil customer requirements.

◦ For example, engines in motor cars are controlled by an on-board


computer that uses quite sophisticated software. Different engines and
cars require slightly different engine-control software, but all engine
controllers are essentially the same.

◦ A manufacturer of engine-control software can produce a series of


engine controllers for different customers, reusing major parts of the
software from customer to customer, with only those parts peculiar to
the particular customer being different.

41
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: the first stage is to recognise that a series of related


software systems do not differ much from each other. This leads to domain
analysis.
2. Domain analysis: existing systems in the domain are examined and domain
experts are consulted.
3. Architecture specification: further analysis leads to the architecture for the
product line.
4. Component collection: in the same way as a framework, each of the reference
architectures will be accompanied by a repository of components that can be
used with it, together with the associated documentation.

 These four stages, which are typically very complex and difficult, establish
the product line from which products can be developed that are tailored to
the needs of individual customers.
42
Section 4: Reusing architecture
For each particular product a further four stages are needed.
5. Specific-requirements capture: specific requirements for the new
product are captured as specialisations and extensions of the domain
model developed in Stage 2.

6. Architecture specialisation: a reference architecture is selected on the


basis of the specific requirements. Changes are made to accommodate
the specialisations and extensions of the domain model corresponding to
the new requirements.

7. Component selection and specialisation: the product that meets the


new requirements is then built, selecting components from the repository
where these exist and adapting them as necessary.

8. Integration and release: finally the components must be integrated into


the architecture – a relatively easy process if the architecture has been
well designed.

43
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.

44
Section 5: Reusing design

 In Section 4 we looked at the reuse of architectures.


 Here we look at design patterns, which represent reusable
solutions to design problems at a more detailed level.
 Usually design patterns only apply in an object-oriented
setting and involve just a few software classes and the
relationships between them.
 Each pattern solves a recognizable problem that crops up
over and over again.
 To understand a design pattern you must first understand
the problem it is trying to solve.

45
Section 5: Reusing design

Adapter design pattern

 A very common situation is to have a client that expects to


make calls to a particular interface but then find it needs to
work with a class that has a different interface.
 This problem is essentially the same as the real-life one
faced by a traveler having an electrical device that won’t plug
in to the local power supply. The solution is an adapter.
 The adapter plugs into the local supply and the device plugs
into the adapter (Figure 18). Figure 18 Adapter

 Suppose you are developing a simple


drawing package. Your design has a
client and a class Square with an
operation draw() (Figure 19).
 When draw() is invoked a square will
draw itself. Figure 19 Initial class design

46
Section 5: Reusing design

 The customer likes this so much that they ask you to add a facility for
rounded squares as well as ordinary ones (Figure 20).
 Luckily another developer has already written a RoundedSquare class for
a different project, so you decide to reuse it. But the RoundedSquare class
has a different interface (Figure 21).
 Where Square has the operation draw() the RoundedSquare class has
render().
 Of course you could modify the client so it used both operations, but you’d
prefer not to have to do that.

Figure 20 Rounded square Figure 20 RoundedSquare class

47
Section 5: Reusing design

 The solution is to introduce an Adapter class (Figure 22).


 The Adapter class extends Square but has a RoundedSquare attribute,
shown as rs : RoundedSquare.

Figure 22 Adapter
48
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 (Figure 23).

Figure 23 Forwarded message


49
Section 5: Reusing design

 Note that:

 The pattern uses inheritance – an Adapter is a Square.


 The pattern uses composition (represented by an association)
– an Adapter has a RoundedSquare as an attribute.
 These two mechanisms are fundamental to design patterns
and many patterns exploit both, as the Adapter pattern does.
 The Adapter is transparent to the other classes – neither the
Client nor RoundedSquare is aware of its existence.

50
Section 5: Reusing design

Interfaces

 The Adapter pattern is concerned with converting between interfaces but


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.
 For this we need the UML notation for an interface. We shall use this
notation frequently later in this unit, and in the next.
 The notation 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.

51
Section 5: Reusing design

 The actual implementation of the operations is defined within classes that realize
the interface.

 A class realizes an interface by defining operations corresponding to those of the


interface, or by inheriting them from another class.

 A class can realize multiple interfaces, in which case the class has to declare all
the operations found in all the interfaces, although it may also have additional
operations.

Figure 24 UML notation for an interface


52
Section 5: Reusing design

 The UML notation for realization of an interface is shown in Figure 25.


 The relationship is indicated by an arrow similar to the one used to show a
generalization relationship, but it uses a dashed line.

Figure 25 Realization of interface


53
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:

1. Creational patterns, which deal with ways of creating


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

54
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.

55
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.

56
Section 5: Reusing design

Figure 26 Adapting an interface

57
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.

58
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.

59
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


MVC structure for a clock system

60
Section 5: Reusing design

 As a real-life analogue for this, craft suppliers sell clock


movements (Figure 27).
 These are the working parts of a clock but without any clock
face or hands.
 Clock builders can then add different clock faces that all use
an identical design for the clockwork (Figure 28).

61
Section 5: Reusing design

Figure 30 MVC structure for data display

62
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.

63
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 (Figure 31).
 You should be able to see that this pattern is closely related to the notification
architectural style.

Figure 31 Subject and observer

64
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 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.

65
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


66
Section 5: Reusing design

Singleton and Factory patterns

 We have looked at an example of a structural design pattern (Adapter)


and at a behavioural pattern (Observer). Next we look at two creational
patterns, Singleton and Factory.

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.

67
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


68
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


69
Section 5: Reusing design

Factory pattern

 A factory is a specialized object for creating and initializing 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.

70
Section 5: Reusing design

Factory pattern
Name. Factory.
Purpose If the creation and initialization 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.

71
Section 5: Reusing design
Factory pattern
When to use Whenever object creation and initialization 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


72
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.

73
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.

74
Section 5: Reusing design

Figure 40 Factory method pattern

75
Section 5: Reusing design

Figure 41 Document factory

76
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.

77
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.

78

You might also like