One of the things I see all the time with developers, especially PHP ones, is a complete lack of understanding for basic computer science principles. Key among those principles missing from many programmers, are design patterns. While it could be said that some folks use design patterns far too much, most software guys / gals (especially freelancers) don’t use them nearly enough.
The idea behind design patterns, is to make routine the typical problems encountered by most software development. It’s likely that any problem get stuck in when trying to write the next biggest app in the world, someone already figured out. So, in much the same way that Object Oriented programming lets applications reuse code, Design Patterns help developers reuse algorithms and ideas.
The most basic, and classic design pattern is the Singleton Pattern. The principle, as you might have figured out, is to ensure singularity of an entity. There are some objects that should never be duplicated throughout the life of an application. Great examples of these are database connectors, request dispatchers, registries, etc …
So, at it’s most basic, a singleton is a class. What make it special, is that it’s constructor is not publicly available. Instead, the instance of the class is publicly available through a special method, getInstance. This function handles the acutally getting of the instance, and prevents duplication of the class.
Easy enough, here’s an example in PHP :
< ?php class Foo { /** * Property to contain the instance of the class * * @var Foo $_instance */ private static $_instance; /** * Privatize the constructor of the class, to prevent the public from getting crazy with it */ private function __construct ( ) { } // END private constructor /** * The function that makes it all happen * * @return Foo */ public static function getInstance ( ) { // IF the _instance property is not already set ... if (! isset(self::$_instance)) { self::$_instance = new self; } // RETURN the instance of self return self::$_instance; } // END getInstance } // END Foo
Related posts:
- Factory Pattern In following the theme of design patterns we’re starting this...
- Observer Pattern One of my favorite design patterns, is theĀ Observer Pattern. TheĀ Observer...
- Decorator Pattern In our ongoing series about design patterns, we introduce the...
Tags: code, coding, design, object, ood, oop, oriented, pattern, programming, singleton