23.07.2012 Views

Design Patterns Explained

Design Patterns Explained

Design Patterns Explained

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

262 Part V • Handling Variations with <strong>Design</strong> <strong>Patterns</strong><br />

Supplement: C++ Code Examples<br />

Example 16-3 C++ Code Fragment: Singleton Pattern<br />

Class USTax<br />

{ public:<br />

static USTax* getlnstance();<br />

private:<br />

USTax(};<br />

static USTax* instance;<br />

}<br />

USTax::USTax ()<br />

{ instance= 0;<br />

}<br />

USTax* USTax::getlnstance () { if<br />

(instance== 0) {<br />

instance= new USTax;<br />

} return<br />

instance;<br />

}<br />

Example 16-4 C++ Code Fragment: Double-Checked Locking Pattern<br />

class USTax : public CalcTax<br />

{ public:<br />

static USTax* getlnstance(};<br />

private:<br />

USTax();<br />

static USTax* instance;<br />

};<br />

USTax::USTax ()<br />

{ instance= 0;<br />

}<br />

USTax* USTax::getlnstance () { if<br />

(instance== 0) {<br />

// do sync here<br />

if (instance== 0) {<br />

}<br />

}<br />

return instance;<br />

}

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

Saved successfully!

Ooh no, something went wrong!