lundi 4 décembre 2006

The default design pattern

For a CORBA school project I made this pattern to deal with several bus. It is similar to the singleton pattern. This pattern is useful if you need the same instance in heighty or ninety percent of cases.

Imagine your application deal with one database. As a good programmer you write a connection pool. Each instance have a host, user and password attributes. After that, you decided to make this class a singleton because you work only with one database. Every thing works well, that seems perfect. Unfortunatly your application is growing and six months later it have to deals in infrequent cases with a second database. Damned, you can't reuse your connection pool because you need two instances of it and that's not possible because your pool is a singleton.

In this case the good solution is to have a default instance. Thus in most case you get the connection pool by the default_instance method . And in the other hand you create new instances. The first call of default_instance will create a new instance and the next will return the created instance. The sample code below show how this design pattern is simple.

require 'default'

class ConnectionPool
include Default # Add a default_instance methode
...
end

# Deal with the main database
pool = ConnectionPool.default_instance
# Deal with the second database
pool = ConnectionPool.new('host', 'name', 'pwd')


You can get the ruby source code here.

Aucun commentaire: