简体   繁体   中英

how to combine singleton and factory design pattern with python?

Suppose there are several presses, each one published many books I am going to handle many records like 'press name, book name'

I want create the class 'Press' by a unique name(string), but only different string can produce different instances of class 'Press'.

so, I need a class work like 'factory', create a new instance when a record contains a new press, but it also work as singleton if there are already exists which has the same names.

You could create a dict with the unique names as keys and Press objects as values. This doesn't need to be a global dict. You can wrap it in some class like that:

class Press:
    def __init__(self, name):
        self.name = name
        self.books = []

class PressManager:
    presses = {}

    @classmethod
    def get_press(cls, name):
        if name not in cls.presses:
            cls.presses[name] = Press(name)
        return cls.presses[name]


example_press = PressManager.get_press("Test")

I implemented get_press() as a class method, because I think this is what you had in mind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM