Presentation on theme: "T O K ILL A S INGLETON F ACTORY M ETHOD P ATTERN Josh Mason 6/18/09."— Presentation transcript:
T O K ILL A S INGLETON F ACTORY M ETHOD P ATTERN Josh Mason 6/18/09
T O K ILL A S INGLETON Will try and answer these important questions Who deletes a singleton? How do you go about deleting a singleton?
O RIGINAL D ESIGN Recall Single Instance of a class Class controls its own creation Not addressed Destructors Deletion/Cleanup Key ideas to keep in mind Destruction order Dangling references Singletons typically long lived
P OSSIBLE S OLUTIONS Explicit destruction *Singleton destroyer *Static function variable
S INGLETON D ESTROYER Static object in Singleton class Manages singleton instance Automagically cleans up Singleton class on program exit Consequences Order of static object destruction undefined (in C++) Requires use of friend keyword to access protected instance Only cleaned up on process termination
S TATIC F UNCTION V ARIABLE Declare instance variable in Instance() as static Return reference to instance variable Automagically cleans up Singleton class on program exit Consequences Don’t need SingletonDestroyer Uses object notation instead of dereference notation (. vs -> in C++) Still doesn’t solve order singletons with mutual dependency Only cleaned up on process termination
F ACTORY M ETHOD P ATTERN Creational Pattern Defines interface for creation of objects, but lets subclasses decide which class to instantiate Defers instantiation to subclasses Commonly used to “refer to any method whose main purpose is creation of objects”
A PPLICABILITY Use the Factory Method Pattern when A class can’t anticipate the class of objects it must create A class wants its subclasses to specify the object it creates Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
C LASS D IAGRAM
P ARTICIPANTS Product Defines product interface Concrete Product Implements Product interface Creator Declares FactoryMethod() May call FactoryMethod() to create object Concrete Creator Overrides FactoryMethod() to return an instance of Concrete Product
C ONSEQUENCES Provides hooks for subclasses Eliminates the need to bind application-specific classes into code. Enables the subclasses to provide an extended version of an object Connects parallel class hierarchies
C ONSIDERATIONS ON I MPLEMENTATION Two major varieties Creator is abstract and provides no default implementation Creator is concrete and provides default implementation Parameterized factory methods Use of templates to avoid subclassing Name factory method appropriately
R ELATED P ATTERNS Abstract Factory Template Method Defers some steps to children. Specifically creation of object Prototype Doesn’t require subclassing Creator. Often require Initialize operation on Product class which Factory Method doesn't require.