multi-instance and classic singleton design patterns

Neil Zanella nzanella at cs.mun.ca
Wed Aug 18 17:54:05 EDT 2004


Hello,

I would be very interested in knowing how the following C++ multi-instance
singleton (AKA Borg) design pattern based code snippet can be neatly coded
in Python. While there may be somewhat unusual places where multi-instance 
singleton is more useful than plain singleton, it seems to me that the
former leads to less coding, so unless I can somehow package the
singleton pattern in a superclass (so I don't have to code it
explicityly in every singleton class I have), then I am more
interested in the multi-instance singleton design pattern.

Thanks,

Neil

#include <iostream>

class B {
  public:
    B() { }
    void foo() const {
      std::cout << x << std::endl;
    }
    void bar() {
      std::cout << y++ << std::endl;
    }
  private:
    static const int x = 0;
    static int y;
};

int B::y = 1;

int main() {
  B().foo();
  B().bar();
  B().foo();
  B().bar();
  B().bar();
}



More information about the Python-list mailing list