Singleton pattern คือ pattern ที่จำกัดการสร้างอ็อบเจ็กต์ให้มีเพียง หนึ่งอินสแตนซ์เท่านั้น Ruby standard library มีโมดูล Singleton ให้ใช้งาน
Singleton Pattern Code Example
ทำให้ new เป็น private และสร้าง class method instance คืนค่าอินสแตนซ์เดียว:
require 'singleton' class Shop include Singleton end Shop.new # NoMethodError: private method `new' Shop.instance.object_id # 5659218 (เสมอเหมือนกัน)
Why You Shouldn’t Use This Pattern (ทำไมควรหลีกเลี่ยง)
Singleton บ่อยครั้งกลายเป็น global variable ทำให้ยากต่อการทดสอบ เพิ่ม coupling Kent Beck กล่าว: "ปัญหาจริงของ Singletons คือให้ข้ออ้างที่ดีเกินไปในการไม่คิดเกี่ยวกับ visibility ที่เหมาะสมของอ็อบเจ็กต์"
ถ้าหลายคลาส depend บน singleton object เดียว การ refactor จะยากมาก
Good Uses? (มีการใช้ที่ดีไหม?)
พบบน Github ใช้ร่วมกับ Null Object pattern Rails ใช้ใน ActionPack:
class AllType < Type
include Singleton
def initialize
super "*/*", :all
end
def all?; true; end
def html?; true; end
end
สรุป: ใช้ได้ในสถานการณ์เฉพาะ แต่ต้องคิดมากก่อนใช้
Summary
เรียนรู้ Singleton pattern การ implement ใน Ruby และเหตุผลที่ควรหลีกเลี่ยงส่วนใหญ่ คุณคิดยังไงกับ pattern นี้? 见过吗?