[Design Patterns]: Singleton

Singleton pattern means allowing access to a single instance of defined class. For example, Mailer class could be reused several times throughout your application to send emails. It doesn’t have to be instantiated several times and you should be able to access the same instance once you need to use the Mailer class. The same applies to the database class. You would like to use existing database connection instead of constructing and creating a spare connection to your database every time you want to execute a query.

Though singleton pattern guarantee that class has only one instance and can be easily accessed a lot of developers consider it as anti-pattern. Singleton pattern may introduce global state in application, unnecessary restrictions and make your code easier to maintain and reuse. Writing tests can be also more complicated.

Majd Arbash

Leave a Reply