Code Anarchy

Oh, Singleton…

Oh, Stack Overflow:

If you had a factory class that creates new objects of some kind, and that factroy class is a singleton, like this:

class Database_Factory extends Base_Factory {
    private static $factory;
    private $objects = array();

    public function __get($profile) {
        // check for object and return it if it's created before
    }

    public static function getInstance(){
        if (!self::$factory)
            self::$factory = new self();
        return self::$factory;
    }
}

The same code repeats anytime where some object needs it's own factory. So i decided to make this factory class abstract and implement only specific routines for each factory. But PHP does not allow to instantiate abstract class.

A few thoughts come to mind:

  1. Why bother with factories at all in PHP? Factories exist to construct objects whose exact types aren't known until runtime. PHP can already do this: new $class_name();
  2. Why bother making the factories singletons? This code doesn't prevent people from making multiple factories of the same type anyway. If there really can only be one (and I can see a use case for that), why not use global variables? Singletons are more or less fancy globals anyway.
  3. If you insist on doing something like this, it calls for a different approach.

Javascript lets you do this:

function make_memoizer(x) {
	var value;
	return function() {
		if(typeof(value) == "undefined")
			value = x();
		return value;
	}
}

var get_counter = make_memoizer(function() {
	var value = 0;
	return {
		nextValue: function() {
			return ++value;
		}
	};
});

document.write('Next value: ' + get_counter().nextValue() + '<br>');
document.write('Next value: ' + get_counter().nextValue() + '<br>');
document.write('Next value: ' + get_counter().nextValue() + '<br>');

This might be one of the many reasons functional programmers often see design patterns as a sign of weakness in object-oriented programming languages. Can your favorite language do this?

PHP can, actually, if you're using 5.3 or newer.

C++ isn't that fancy1, but it does give you templates, which let you do some pretty whacky things. This is probably one of the tamer examples2:

template <typename T>
class Singleton {
private:
	static T *instance;
public:
	static T* getInstance() {
		if(!instance) {
			T* new_instance = new T();
			if(__sync_val_compare_and_swap(&instance, 0, new_instance))
				delete new_instance;
		}
		return instance;
	}
};

// Example

class GlobalCounter : public Singleton<GlobalCounter> {
private:
	int counter;
	GlobalCounter() { counter = 0; }
public:
	int nextValue() { return __sync_add_and_fetch(&counter, 1); }

	friend class Singleton<GlobalCounter>;
};

// Why oh why does the language make me do this bit?
template<> GlobalCounter *Singleton<GlobalCounter>::instance = 0;

int main(int argc, char *argv[]) {
	cout << "Next value: " << GlobalCounter::getInstance()->nextValue() << endl;
	cout << "Next value: " << GlobalCounter::getInstance()->nextValue() << endl;
	cout << "Next value: " << GlobalCounter::getInstance()->nextValue() << endl;
}

It's still pretty verbose, but it's a bit less verbose than writing 300 versions of getInstance(), all alike.

If your language is making you hand-roll singletons over and over again, maybe it's time to find a new language. Your relationship just isn't healthy.

1 C++11 is, I believe, actually almost that fancy.

2 A note on thread-safety: this example makes the assumption that it's safe to accidentally construct multiple copies of the singleton, as long as the rest of the application only ever sees one official copy.