01.02.2013 Views

Software Development Cross Solution - Index of - Free

Software Development Cross Solution - Index of - Free

Software Development Cross Solution - Index of - Free

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.

switching to test code with the strategy pattern<br />

The strategy pattern provides for multiple<br />

implementations <strong>of</strong> a single interface<br />

We want to hide how the system gets gift cards, and vary it depending on<br />

whether we’re testing the code or we’re running the system in production. Flip<br />

to Chapter 1 <strong>of</strong> Head First Design Patterns and you’ll find there’s a ready made<br />

pattern to help us deal with just this problem: the strategy pattern.<br />

We can provide two different<br />

implementations: one for when<br />

we’re testing, that doesn’t really<br />

296 Chapter 8<br />

<br />

DBAccessor<br />

+ getGC(gcId : int) :GiftCard<br />

+ saveGC(card : GiftCard) :void<br />

+ saveOrder(orderInfo : OrderInformation)<br />

With the strategy pattern<br />

you provide an interface<br />

specification for the<br />

algorithm you want to vary.<br />

hit a database, and.......one that actually hits the<br />

TestDBAccessor<br />

+ getGC(gcId : int) :GiftCard<br />

+ saveGC(card : GiftCard) :void<br />

+ saveOrder(orderInfo : OrderInformation)<br />

Now we’ve got two different ways <strong>of</strong> hitting the database, and<br />

OrderProcessor doesn’t need to know which one it’s using.<br />

Instead, it just talks to the DBAccessor interface, which hides<br />

the details about which implementation is actually used.<br />

All we need to do now is add a way to give the OrderProcessor<br />

the correct DBAccessor implementation, based on whether the<br />

test code or the system is providing it.<br />

OrderProcessor<br />

- dbAccessor : DBAccessor<br />

+ setDBAccessor(DBAccessor) : void<br />

+ procesOrder(orderInfo : OrderInformation) : Receipt<br />

Download at WoweBook.Com<br />

database. This class can be<br />

written later, as part <strong>of</strong> the<br />

database task.<br />

MySqlDBAccessor<br />

+ getGC(gcId : int) :GiftCard<br />

+ saveGC(card : GiftCard) :void<br />

+ saveOrder(orderInfo : OrderInformation)<br />

* If your customer was unsure<br />

about what database they<br />

might use in production, this<br />

same approach would make it<br />

easy to swap out database<br />

vendors and implementations.<br />

The strategy pattern<br />

encapsulates a family <strong>of</strong><br />

algorithms and makes<br />

them interchangeable.

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

Saved successfully!

Ooh no, something went wrong!