หน้าแรก > PHP-MySQL > singleton pattern

singleton pattern

กุมภาพันธ์ 5, 2008 ใส่ความเห็น Go to comments

หลัง ๆ มารู้สึกประทับในใน singleton pattern

ลองเขียนด้วย php ได้แบบนี้ครับ

class TestClass{

private static $instance;

public static function get_instance()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
}

ในบาง instance เราไม่คงไม่ต้องการใช้บ่อยนัก หรือ ไม่จำเป็นต้องสร้างขึ้นมาใหม่
เช่น  instance  ที่ได้ จาก factory pattern  ไม่จำเป็นต้องใช้หลาย instance เลย
ดังนั้นเราจึงควรออกแบบ factory class ให้เป็น singleton pattern
เฮ่อ ๆ ๆ แต่นั่นเป็นเพียงตัวอย่างที่ยกขึ้นมาอธิบายเพียงคร่าว ๆ ครับ

Categories: PHP-MySQL
  1. กุมภาพันธ์ 24, 2008 ที่ 2:57 pm | #1

    singleton นี่ดาบหลายคมนะครับ ใช้อย่างระวังอย่าให้มันเยอะเกินงาม ต้องคิดเยอะๆ ก่อนเลือกใช้ครับ : )

  2. กุมภาพันธ์ 24, 2008 ที่ 3:34 pm | #2

    เจ๋งดีว่ะน้องเอาอีกๆ

  1. No trackbacks yet.

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Connecting to %s

Follow

Get every new post delivered to your Inbox.