Skip to Content
เมนู
คุณต้องลงทะเบียนเพื่อโต้ตอบกับคอมมูนิตี้
คำถามนี้ถูกตั้งค่าสถานะ
1 ตอบกลับ
4711 มุมมอง

Is it possible to implement singleton design pattern in odoo framework. 

อวตาร
ละทิ้ง
คำตอบที่ดีที่สุด

Yes, it is possible to implement the singleton design pattern in the Odoo framework. To do this, you can create a base model with a class method that returns the same instance of the model each time it is called. The model would be initialized with a default value, and any subsequent calls to the class method would return that initialized instance. Here is an example:

class MyModel(models.Model):
    _name = 'my.model'

    def __init__(self):
        self.value = 0

    @classmethod
    def get_instance(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = MyModel()
        return cls.instance

In this example, MyModel.get_instance() would always return the same instance of MyModel, with the value attribute initialized to 0. You can then use this instance in your code as needed. Note that this implementation of the singleton pattern is not thread-safe, so you may need to add additional logic to ensure that multiple threads cannot access the instance at the same time.

อวตาร
ละทิ้ง