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.

156 Chapter 12 ■ Design patterns<br />

><br />

createImage is class (static) method of the class Image. It looks at the extension of<br />

the file name parameter and creates an appropriate object. For example, if the file type<br />

is jpeg, it creates a subclass of Image suitable <strong>for</strong> jpeg images. The sole purpose of this<br />

method is to create the appropriate object, making the choice at run time. So now users<br />

can treat all image file types in the same manner. The code <strong>for</strong> the factory method is:<br />

class Image {<br />

}<br />

public static Image createImage(String fileName) {<br />

String extension = getExtension(fileName);<br />

if (extension.equals("jpeg"))<br />

return (new JpegImage(fileName));<br />

if (extension.equals("gif"))<br />

return (new GifImage(fileName));<br />

}<br />

Here we have used a method getExtension (not shown) that returns the extension<br />

part of a file name.<br />

We have buried the code that creates an appropriate class within the factory method,<br />

providing a simple interface to the users.<br />

Why could we not simply use the constructor method of class Image? The answer is<br />

that a constructor can only return an object of its own class. This is a limitation of constructors<br />

and, if we need to do anything different, we need to use a factory method.<br />

12.6 ● Façade<br />

Suppose you write a group of classes that per<strong>for</strong>m some useful functions. It could be a<br />

filing system that allows other classes (users) to open a file, close a file, read and write<br />

in<strong>for</strong>mation. One option is to tell users which classes to use and how (Figure 12.3, lefthand<br />

diagram). However, this means that a user needs to understand the structure of<br />

the subsystem to use it effectively. In addition, changes to the structure of the subsystem<br />

may require changes to its users.<br />

A better option (Figure 12.3, right-hand diagram) is to tell users to use one class –<br />

a façade class. The façade class presents a clean and simple interface <strong>for</strong> users. It has<br />

Figure 12.3 The Façade pattern<br />

User<br />

User<br />

Façade<br />

>

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

Saved successfully!

Ooh no, something went wrong!