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.

12.5 Factory method 155<br />

The following coding shows how a singleton class Demo can be written in Java.<br />

public class Demo {<br />

}<br />

private static final Demo demo = new Demo();<br />

private Demo() {<br />

}<br />

private static Demo getInstance() {<br />

return demo;<br />

}<br />

SELF-TEST QUESTION<br />

12.2 Why is the constructor Demo labeled as private?<br />

12.5 ● Factory method<br />

Suppose that we are writing some software to handle images. An image resides in a file<br />

and there are several different common file <strong>for</strong>mats – <strong>for</strong> example, jpeg and gif. We would<br />

like the facility to create an object corresponding to a graphics image, in this manner:<br />

Image image = new Image("picture.jpeg");<br />

Once we have created the object, we can per<strong>for</strong>m such operations as:<br />

image.rotate(90);<br />

image.display();<br />

image.enlarge(2, 2);<br />

The problem is that all of these methods will be different <strong>for</strong> each different graphics<br />

file <strong>for</strong>mat. Indeed, the graphics object will be different <strong>for</strong> each file <strong>for</strong>mat. So one single<br />

class – Image – will not suffice; we need a different class <strong>for</strong> each file <strong>for</strong>mat. One<br />

approach would be to provide a number of classes and expect a user to call the constructor<br />

<strong>for</strong> the relevant class like this:<br />

JpegImage image = new JpegImage("fileName.jpeg");<br />

But this is clumsy. The alternative is to create an abstract class Image that has a factory<br />

method createImage. Now we create an image object conveniently like this:<br />

Image image = Image.createImage("fileName.jpeg");<br />

>

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

Saved successfully!

Ooh no, something went wrong!