Thursday, March 4, 2010

Singleton Pattern Design for Python

There are three categoris of OO Patterns:
  1. Creational - patterns that can be used to create objects
  2. Structural - patterns that are used to combine object and classes in order to build structured objects
  3. Behavioral - patterns that can be used to build computation and control the flow of data
Creational Example:

A Singleton is a way to ensure that you cannot create more than one instance of a class. A class attribute could be used to check the number of instantiations of the class.
The singleton patter requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made protected.
As a note: "The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation." ~From http://en.wikipedia.org/wiki/Singleton_pattern

Here are two examples of Singleton Patterns:

This will produce an output of:
Here is a second singleton implementation that returns the same instance of the singleton instead of throwing an error:


I would recommend starting to use Design Patterns in your ArcGIS Python code. With the coming of 10, it will be more important than ever to have code that conforms to standard coding practices.

The goal of any OO programming is the following:
  1. Genericity - is a technique to define parameters for a module exactly as you define parameters for a function thus making the module more general
  2. Flexibility - very difficult to achieve, but functions should be written as general as possible to allow for multiple data types
  3. Inheritance - is the ability in OO Programming to derive a class from another, either by extending it or specialize it
  4. Overloading - refers to the possibility for an operator or method to behave differently according to the actual data types of their arguments
  5. Polymorphism - is the possibility for something to have several forms.