21.08.2013 Views

Software Engineering for Students A Programming Approach

Software Engineering for Students A Programming Approach

Software Engineering for Students A Programming Approach

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

158 Chapter 12 ■ Design patterns<br />

These relationships between components are the essence of the MVC pattern. The<br />

advantages are that the model, the view or the controller can be changed without<br />

affecting any other part of the system. Furthermore, additional views and controls can<br />

be added easily.<br />

12.9 ● Mediator<br />

In the software <strong>for</strong> the cyberspace invaders game, there must be a method or methods<br />

that test to see whether a laser has hit an alien and whether a bomb has hit the<br />

defender. The question is: Where are these methods? One option is to place this collision<br />

detection within class Laser and class Bomb. Un<strong>for</strong>tunately this leads to a complex<br />

structure in which every bomb has to know about the defender object and every<br />

laser has to know about every alien object. This is high coupling. For example, if we<br />

introduce additional objects into the game we will need to modify class Bomb and<br />

class Laser.<br />

A better approach is to create a mediator class. As its name suggests, this is responsible<br />

<strong>for</strong> handling relationships between objects – termed colleague objects. The<br />

essence of the mediator pattern is that colleague objects are changing (because, in this<br />

example, they are moving).<br />

This is how the pattern is implemented. First, all the colleague objects register with<br />

the mediator object. Thereafter, when a colleague object changes its state (in this example,<br />

when it moves) it calls the mediator object. The mediator decides whether a<br />

notable event has occurred (a collision in this example) and, if necessary, notifies appropriate<br />

colleague objects (the objects involved in the collision).<br />

The advantages are:<br />

■ all the dependency logic is in one place<br />

■ the colleague objects are simpler because they do not embody code to check<br />

dependencies.<br />

SELF-TEST QUESTION<br />

12.3 Identify differences between the Mediator pattern and the MVC pattern.<br />

12.10 ● Pipe and Filter<br />

This pattern describes a way of building software from a group of components that<br />

collaborate by passing a stream of in<strong>for</strong>mation. The components behave like an<br />

assembly line. Each component inputs some in<strong>for</strong>mation from one component,<br />

processes it and passes it on to another component, Figure 12.4. Each component is

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!