آموزش Singleton Design Pattern

Image تحقیقات

آموزش Singleton Design Pattern

سلام خدمت شما دوستان

امروز میخوام به معرفی یک Design Pattern (دیزاین پترن) در زبان php به نام Singleton بپردازم.

این Design Pattern برای مواقعی کاربرد داره که مثلا بخواهیم فقط یک شی از کلاس  php ساخته شود و بیشتر از یک شی نتوان از کلاس ساخت و از ان جلوگیری شود.

مثلا یک کلاس داریم برای ارتباط با دیتابیس.خب لازم نیست بیشتر از یک شی و یک ارتباط با دیتابیس ایچاد شود. پس باید کاری کنیم که نشه بیشتر از یک شی (object) از آن کلاس ساخت.

چندتا نمونه کد اینجا براتون قرار میدم که همشون در اصل یک کار رو انجام میده با کمی تفاوت در نوع کد نویسی.

آمزوش Singletone

آمزوش Singletone

مثال :

Hello, this method is called by using a singleton object..';
26.
}
27.
}//END Class
28.
 
29.
///Testing some calls to that class
30.
$obj1 = MySingletonClass::getInstance();
31.
$obj2 = MySingletonClass::getInstance();
32.
$obj3 = MySingletonClass::getInstance();
33.
 
34.
$obj1->GreetMe();
35.
$obj2->GreetMe();
36.
$obj3->GreetMe();

 مثال :

class MySingletonClass
{
    ///Condition 1 - Presence of a static member variable
    private static $_instance = null;

    ///Condition 2 - Locked down the constructor
    private function  __construct() { } //Prevent any oustide instantiation of this class

    ///Condition 3 - Prevent any object or instance of that class to be cloned
    private function  __clone() { } //Prevent any copy of this object

    ///Condition 4 - Have a single globally accessible static method
    public static function getInstance()
    {
        if( !is_object(self::$_instance) )  //or if( is_null(self::$_instance) ) or if( self::$_instance == null )
            self::$_instance = new MySingletonClass();
        return self::$_instance;
    }

    ///Now we are all done, we can now proceed to have any other method logic we want

    //a simple method to echo something
    public function GreetMe()
    {
        echo '
Hello, this method is called by using a singleton object..';
    }
}//END Class

///Testing some calls to that class
$obj1 = MySingletonClass::getInstance();
$obj2 = MySingletonClass::getInstance();
$obj3 = MySingletonClass::getInstance();

$obj1->GreetMe();
$obj2->GreetMe();
$obj3->GreetMe();

 

حلسه ی آموزشی ما به پایان رسید

جلسات بعدی رو حتما دنبال نمایید.