diff --git a/README.md b/README.md index 1e012055..810cdd0e 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ __Creational Patterns__: | [lazy_evaluation](lazy_evaluation.py) | lazily-evaluated property pattern in Python | | [pool](pool.py) | preinstantiate and maintain a group of instances of the same type | | [prototype](prototype.py) | use a factory and clones of a prototype for new instances (if instantiation is expensive) | +| [singleton](singleton.py) | use a singleon instances | __Structural Patterns__: diff --git a/singleton.py b/singleton.py new file mode 100644 index 00000000..7e0bb972 --- /dev/null +++ b/singleton.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +class Singleton(object): + _instance = None + + def __new__(cls, *args, **kwargs): + if not isinstance(cls._instance, cls): + cls._instance = object.__new__(cls, *args, **kwargs) + return cls._instance + + +class Account(Singleton): + pass + + +class Test(Singleton): + pass + + +if __name__ == '__main__': + a = Account() + b = Account() + c = Test() + d = Test() + print 'a: %s\r\nb: %s\r\nc: %s\r\nd: %s' % (a, b, c, d)