Top Banner
Introductio n to Patterns Michael Heron
35

PATTERNS01 - An Introduction to Design Patterns

Nov 01, 2014

Download

Software

Michael Heron

An introduction to design patterns in object orientation. Suitable for intermediate to advanced computing students and those studying software engineering.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: PATTERNS01 - An Introduction to Design Patterns

Introduction to PatternsMichael Heron

Page 2: PATTERNS01 - An Introduction to Design Patterns

Introduction In the beginning there was the code.

And the code was without form. And programmers said

Let there be functions. And programmers saw the functions,

and saw that they were good. And then the programmer said.

Let there be objects.

Page 3: PATTERNS01 - An Introduction to Design Patterns

Object Oriented Programming Objects represent an excellent tool for

developing object oriented programs. However, like anything they can be used badly.

There are issues of scale that come along with developing an object oriented program. Many objects can become unmanageable. Coupling and Cohesion are constant problems.

A good class has high cohesion. Related methods and attributes are

encapsulated together.

Page 4: PATTERNS01 - An Introduction to Design Patterns

Object Oriented Programming For large programs, objects soon become

difficult to manage. Too many classes Too many interrelationships. Unordered and difficult to gain a broad view.

Good designs require a higher level abstraction. Abstractions that consist of related groups of

objects.

Page 5: PATTERNS01 - An Introduction to Design Patterns

Objects – Bare Bones What defines an object?

Objects have attributes (defined in the class) Objects have behaviors (defined in the class) Object have a state

A better view is that an object is a cog in a more complicated machine. It is a moving part with a specific

responsibility in a system. Representing a certain kind of unit, for

example.

Page 6: PATTERNS01 - An Introduction to Design Patterns

Building Objects How do we build objects?

There are several methods. Natural language analysis is a useful tool.

Underline nouns, verbs and adjectives in a requirements document.

Organic evolution Start with a class, build on it from there.

Pattern based analysis Analyse the overall structure of the system. Create classes to fill specific roles.

Page 7: PATTERNS01 - An Introduction to Design Patterns

Coupling and Cohesion One of the biggest problems OO developers

have is ensuring a good OO design. What is a good OO design, you ask?

Certainly for people unfamiliar with how OO is best done, it’s hard to objectively rate an object architecture.

Two objective measures exist for this though. As a rule, we are aiming for high cohesion

and low coupling.

Page 8: PATTERNS01 - An Introduction to Design Patterns

Coupling Coupling relates to the amount of

interconnectedness of classes. We want this to be as low as is reasonably

possible. A coupling relationship is any composition,

aggregation, or inheritance. The more connections made between

objects and classes, the harder it is to make any changes. Because of the knock-on effect associated.

Page 9: PATTERNS01 - An Introduction to Design Patterns

Coupling If your program has high coupling, there are

several disadvantages built in: Changes in one object may result in unexpected

side-effects elsewhere in a program. Often the cause is not at all obvious.

Classes are difficult to understand at a glance. They make use of so much external functionality.

Classes are difficult to test. They cannot be easily extracted from their context.

Page 10: PATTERNS01 - An Introduction to Design Patterns

Coupling There are several types of coupling that exist.

It’s not just the amount of coupling that matters, but also the type of coupling.

Content coupling is when one class directly accesses data local to another class. This is terrible and should be avoided always.

Data coupling is when a public interface is used to exchange to exchange parameters. This is better.

There are other kinds. We don’t have to go into them to any great degree for

now.

Page 11: PATTERNS01 - An Introduction to Design Patterns

Cohesion Cohesion is the level to which an object

adheres to a single set of responsibilities. We want this as high as is reasonably possible.

In a good object oriented program, each object has one firmly defined responsibility. If you have a BankBalance class, it should

contain only the functionality for manipulating the balance.

It should not contain, for example, the address of its owner.

Page 12: PATTERNS01 - An Introduction to Design Patterns

Cohesion The dangers that come from low cohesion are

the same as that of high coupling. They’re really just two ways of reflecting the

same basic concept. Low cohesion is an insidious problem.

Programs with low cohesion tend to become even less coherent over time.

It is a consequence of badly analysed and badly designed programs. You’ll learn how to do this properly in third year.

Page 13: PATTERNS01 - An Introduction to Design Patterns

The Tension of OO Development Object Oriented programs are a tension

between coupling and cohesion. We increase cohesion by increasing

coupling. We reduce coupling by decreasing

cohesion. As OO developers we have to find a happy

medium between the two. In some cases, simple rationalisation of a

design can remove problems.

Page 14: PATTERNS01 - An Introduction to Design Patterns

Design Patterns Design patterns fill the role of ‘high level design’

in object oriented programs. They are a shorthand for particular collections of

objects, arranged in a particular way. Design patterns are battle-tested.

A pattern only enters into common acceptance when it has been shown to work in many situations.

Design patterns are generalised. A design pattern is to object design what an

algorithm is to lines of code.

Page 15: PATTERNS01 - An Introduction to Design Patterns

Design Patterns Design patterns fall into one of several broad

categories. There are some competing definitions for these.

In this module we’ll look at three families of design patterns. Creational Patterns Behavioural Patterns Structural Patterns

There are more, but these will give you a grounding in the selection and use of patterns.

Page 16: PATTERNS01 - An Introduction to Design Patterns

Unified Modeling Language We are going to use a shorthand notation

form to represent design patterns. UML Class Diagrams – you may have

encountered these before. We will very briefly review them today.

So that you can recognize what is happening when they are used later.

It’s important for developers to have a shared vocabulary for discussing design issues.

Page 17: PATTERNS01 - An Introduction to Design Patterns

Object Oriented Programs The relationship between objects and

classes becomes very complex in many computer programs.

Some means of representing this complexity ‘at a glance’ is useful. This is what a class diagram is used for. It gives the static view of a program’s

architecture. Other techniques exist too.

They vary in effectiveness.

Page 18: PATTERNS01 - An Introduction to Design Patterns

Class Diagrams At their simplest,

class diagrams are just boxes with lines connecting them to other boxes. They show the

relationship between classes only.

Page 19: PATTERNS01 - An Introduction to Design Patterns

Class Diagrams At the next level of usefulness, class

diagrams also contain information about attributes and methods. Attributes in the second row Methods in the third

At their best, class diagrams contain class relationships, methods, attributes, and the visibility of each. They also explicitly show multiplicity.

Page 20: PATTERNS01 - An Introduction to Design Patterns

Class Diagram with Attributes

Page 21: PATTERNS01 - An Introduction to Design Patterns

Why Use A Class Diagram? There are several reasons why using a

class diagram leads to a more complete view of a project. It shows the relationship between classes in a

way that allows you to trace accessibility. It shows at a glance the amount of coupling

in a project. It shows at a glance the amount of cohesion

in a project. It shows at a glance the impact of change.

Page 22: PATTERNS01 - An Introduction to Design Patterns

Representing Design Patterns A design pattern is a collection of (usually)

several different classes. It defines the interaction of these objects at a

higher level of abstraction. There are several kinds of documentation for

patterns. The one in most common usage is the Pattern

Language devised by the Gang of Four in the book Design Patterns. We’re not going to get bogged down in the

details.

Page 23: PATTERNS01 - An Introduction to Design Patterns

Benefits of Patterns Part of what design patterns bring to the

field of software engineering is a common vocabulary for design Shorthand solutions for certain kinds of

recurring programming problems. Design patterns are ‘best practice’, and

thus allow for portability of the ‘lessons learned’ of experienced developers. They are an aid to learning.

Page 24: PATTERNS01 - An Introduction to Design Patterns

Benefits of Patterns They fit in easily with existing modern

programming techniques. Design patterns complement object

orientation and agile development. Design patterns reduce the need for

future large-scale refactoring. Tried and tested, and the result of

successive refactoring of their own.

Page 25: PATTERNS01 - An Introduction to Design Patterns

Criticisms of Patterns Some of the patterns that are in common usage are

simple workarounds for missing language features. Some patterns are repetitions of things supported

syntactically in other languages. Can lead to systems that are heavily over-engineered.

Use with care. When you have a hammer…

Patterns represent good solutions to recurring problems, but they are no substitute for effective analysis.

Counter-productive when building expertise. You learn more from failure than you do from success.

Page 26: PATTERNS01 - An Introduction to Design Patterns

The Model View Controller Before we look at the various kinds of design

patterns, I want to spend the rest of this lecture discussing the one most critical to modern programs. It is the Model View Controller Architecture.

It is a design pattern through which maximum flexibility is maintained for the developer. It allows for easy portability between

functionality and interface. It is an example of a structural pattern.

Page 27: PATTERNS01 - An Introduction to Design Patterns

Setting the Scene Imagine this!

Mister Moneybags, hugely successful software publisher, comes to you and says ‘Code me a fruit machine’

You go away, open up Eclipse and develop the best fruit machine anyone has ever seen!

Mister Moneybags says, ‘Excellent work! Now I want it so that we can put a dozen different games onto the same codebase’

Page 28: PATTERNS01 - An Introduction to Design Patterns

Horrors! The monolithic design of putting all code

into a single class (or even several classes) has one big issue. Reusability.

It is common practice for beginning developers to embed functionality into the code that handles the presentation. What this does is tightly bind your

functionality to the context in which it is delivered.

Page 29: PATTERNS01 - An Introduction to Design Patterns

MVC The Model View Controller architecture

addresses this by providing a clean separation of roles in a program. The Model, which handles the ‘business logic’ The view, which handles the presentation of the

state of the model to the user The controller, which allows for the user to

interact with the model. In simple programs, the view and the controller

may be the same class. Often they will not be.

Page 30: PATTERNS01 - An Introduction to Design Patterns

MVC - Model The model defines all the state and functionality of

a system. Everything except presenting information to the user.

The model makes no assumptions with regards to the view of the data. It doesn’t matter to the model if the view is a GUI, a

phone display, or a text interface. The model may be represented by a single class.

More usually, it will be represented by several classes.

Page 31: PATTERNS01 - An Introduction to Design Patterns

MVC - View The view handles the presentation.

It’s the user interface. The view has absolutely no code for

altering the state of the system. It sends queries to the model, and the model

sends the answers back. The only code contained within the view is

view-specific code. Turn an array of strings into a combo box, as

an example.

Page 32: PATTERNS01 - An Introduction to Design Patterns

MVC - Controller The controller is what provides the user’s

ability to manipulate the system. It’s usually represented by the event handlers

for the controls that belong to the view. In an ideal world, the controller is an

entirely separate class to the view. For small, simple programs this is often over-

engineering. The controller defines the ‘stitching’

between the view and the model.

Page 33: PATTERNS01 - An Introduction to Design Patterns

The MVC The MVC is a ‘mega pattern’

Usually its constituent bits will be made up of other patterns themselves.

The separation of the model and the view is the key to the pattern.

By default, Visual Studio will couple the view and controller into a single class. This is not bad strictly speaking, but

something that can be altered for complex systems.

Page 34: PATTERNS01 - An Introduction to Design Patterns

Value of Decoupling Why is it so important we separate out the

model from the view? Division of responsibilities allows for parallel

development. Model best handled by technical teams. View best handled by graphical, UI specialists. All that teams must agree on is the interface

between the different parts of the system. It allows for flexibility of deployment.

A new interface can be ‘bolted on’ with minimal difficulty.

Page 35: PATTERNS01 - An Introduction to Design Patterns

Summary Design patterns are awesome. They are an aggregate abstraction for

interactions of objects. The patterns we will discuss belong to three

main families. Creational Structural Behavioral

Design patterns lead to good OO programs. With the caveat that they can also lead to heavily

over-engineered systems if used indiscriminately.