Factory Method Chris Colasuonno Also known as “Virtual Constructor”
-
Upload
angel-parks -
Category
Documents
-
view
212 -
download
0
Transcript of Factory Method Chris Colasuonno Also known as “Virtual Constructor”
Factory Method
Chris Colasuonno
Also known as “Virtual Constructor”
Factory Method: Defined
Define an interface for creating an object, but let the subclasses decide which class to instantiate.
(Factory Method lets a class defer instantiation to subclasses)
(Gamma et al. 107)
Factory Method: Defined
Creational
Factory Method: Motivated
DocumentApplication
CreateDocument()
NewDocument()
Open Document()
Document* doc=CreateDocument();docs.Add(doc);doc->Open();
Return new MyDocument
MyDocument
MyApplication
CreateDocument()
Open()Close()Save()
Factory Method: Motivated
Factory Method: Applied When should we use Factory Method? When a class:
Can’t predict the class of the objects it needs to create
Wants its subclasses to specify the objects that it creates
Delegates responsibility to one of multiple helper subclasses, and you need to localize the knowledge of which helper is the delagte
Factory Method: The Consequences
Advantage: Elminates the need to bind application-
specific classes to your code. Code deals only with the Product
interface (Document), so it can work with any user-defined ConcreteProduct (MyDocument)
Factory Method: The Consequences
Potential Disadvantages Clients may have to make a subclass of
the Creator, just so they can create a certain ConcreteProduct.
This would be acceptable if the client has to subclass the Creator anyway, but if not then the client has to deal with another point of evolution.
Factory Method: The Consequences
In addition: “Provides hooks for subclasses” “Connects parallel class hierarchies” P.109-110
Factory Method: Implemented
Two major varieties Parameterized factory methods Language-specific issues Using templates to avoid subclassing Naming conventions
Factory Method: Known Uses
Frameworks Toolkits
Factory Method: Related Patterns
Abstract Factory is often implemented with Factory Method.
Usually called in Template Methods Prototypes don’t subclass the Creator,
but often need to initialize the Product class. Creator would use Initialize on the object, but Factory Method doesn’t need this operation.
Sources Gammal et al. Design Patterns: Elements of Reusable
Object-Oriented Software. Addison-Wesley. 1995. Data and Object Factory. Image: Factory.gif Internet.
Available by HTTP: http://www.dofactory.com/patterns/PatternFactory.aspx
Factory Method: Notes Text Books pages 107-116 Slides available at www.rpi.edu/~colasc