[PHP]php 로 구현된 singleton 패턴

ITWeb/개발일반 2008. 4. 14. 21:19
php 로 구현된 singleton 패턴
- prototype 과 singleton
- javascript object, class & inheritance, sigletons

class singleton
// ensure that only a single instance exists for each class.
{
    function &getInstance ($class, $arg1=null)
    // implements the 'singleton' design pattern.
    {
        static $instances = array();  // array of instance names

        if (array_key_exists($class, $instances)) {
            // instance exists in array, so use it
            $instance =& $instances[$class];
           
        } else {
            // load the class file (if not already loaded)
            if (!class_exists($class)) {
                switch ($class) {
                    case 'date_class':
                        require_once 'std.datevalidation.class.inc';
                        break;

                    case 'encryption_class':
                        require_once 'std.encryption.class.inc';
                        break;

                    case 'validation_class':
                        require_once 'std.validation.class.inc';
                        break;

                    default:
                        require_once "classes/$class.class.inc";
                        break;
                } // switch
            } // if

            // instance does not exist, so create it
            $instances[$class] = new $class($arg1);
            $instance =& $instances[$class];
        } // if

        return $instance;

    } // getInstance
   
} // singleton

ref. http://www.tonymarston.net/php-mysql/singleton.html

뭐 위에 다른 글에서도 설명 되어 있지만 어떤 language 로 구현을 하던 최대 N 개로 제한 되어 지는 극한까지는 1개로 제한 되어 지는 객체를 생성 하는 패턴 방식입니다.

더 쉽게 설명 하자면 그냥 global class ,variable  또는 static 이라고도 할 수도 있겠죠.
물론 의미적으로 통할 수 있다는 설명 입니다.
근데 뭐 쉽게 이해 하는데 이 정도면 되지 않나 싶기도 하구요.. ^^*
전 어려운 용어나 개념은 별로 좋아라 하지 않아서.. ㅎㅎ
: