Ciao a tutti. Sto sviluppando una applicazione Python e mi sono trovato a dover implementare il pattern Singleton, seguendo quanto descritto in [1]. Ho trovato diverse soluzioni su internet già scritte quindi il mio lavoro si è trasformato nel dover scegliere quella che sembrava adattarsi meglio alla vera natura del problema ed alla più corretta implementazione della soluzione. La mia scelta si è abbattuta sulla soluzione riportata nella mail, perfettamente funzionante e secondo me ben implementata (trovata in un commento di [2]) Ci sono però nel listato delle parti che non ho capito bene e che vorrei portare all'attenzione della lista.
1) La classe TestSingletonHelper è una classe "interna" alla classe TestSingleton, ed ha il metodo __call__ Questo serve per rendere di fatto privato l'__init__ della classe TestSingleton, che così viene reso inaccessibile. Perchè si è reso necessario l'uso di __call__? cosa realizza di preciso? 2) def __call__( self, *args, **kw ) : perchè a __call__ viene passato *args, **kw ? Cosa sono? a cosa servono e quando secondo voi vengono usati? Grazie a tutti per l'attenzione. Cordiali saluti. Marco Meoni. -- Riferimenti -- [1] Gamma, Helm, et al, "Design Patterns - Elements of Reusable Object-Oriented Software". Addison-Wesley, 1995, ISBN 0-201-63361-2. [2] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 -- Codice -- class TestSingleton : # Create a class variable that will hold a reference # to the single instance of TestSingleton. instance = None # Define a helper class that will override the __call___ # method in order to provide a factory method for TestSingleton. class TestSingletonHelper : def __call__( self, *args, **kw ) : # If an instance of TestSingleton does not exist, # create one and assign it to TestSingleton.instance. if TestSingleton.instance is None : object = TestSingleton() TestSingleton.instance = object # Return TestSingleton.instance, which should contain # a reference to the only instance of TestSingleton # in the system. return TestSingleton.instance # Create a class level method that must be called to # get the single instance of TestSingleton. getInstance = TestSingletonHelper() # Initialize an instance of the TestSingleton class. def __init__( self ) : # Optionally, you could go a bit further to guarantee # that no one created more than one instance of TestSingleton: if not TestSingleton.instance == None : raise RuntimeError, 'Only one instance of TestSingleton is allowed!' #Continiue initialization... # Test this implementation of the Singleton pattern. All of the # references printed out should have the same address. if __name__=="__main__": for i in range( 10 ) : s = TestSingleton.getInstance() print s # This call should raise a RuntimeError indicating # that a single instance of TestSingleton already exists. TestSingleton() -- Sbaush
_______________________________________________ Python mailing list Python@lists.python.it http://lists.python.it/mailman/listinfo/python