Supplement: C++ Code Examples

Example 16-3. C++ Code Fragment: Singleton Pattern
Class USTax {
  public:
    static USTax* getInstance();
  private:
    USTax();
    static USTax* instance;
}
USTax* USTax::instance= 0;

USTax* USTax::getInstance () {
  if (instance== 0) {
     instance= new USTax;
  }
return instance;
}
Example 16-4. C++ Code Fragment: Double-Checked Locking Pattern
class USTax : public CalcTax {
  public:
    static USTax* getInstance();
  private:
    USTax();
    static USTax* instance;
};
USTax* USTax::instance= 0;

USTax* USTax::getInstance () {
  if (instance== 0) {
    // do sync here
    if (instance== 0) {
        instance= new USTax;
    }
  }
  return instance;
}

Get Design Patterns Explained: A New Perspective on Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.