Top Banner
Factory Method A Creational Design Pattern
6

Factory Method A Creational Design Pattern. Factory Method Key Features Defines an interface for creating objects without needing to know each object’s.

Dec 31, 2015

Download

Documents

Luke Clark
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Factory Method A Creational Design Pattern. Factory Method Key Features  Defines an interface for creating objects without needing to know each object’s.

Factory MethodA Creational Design Pattern

Page 2: Factory Method A Creational Design Pattern. Factory Method Key Features  Defines an interface for creating objects without needing to know each object’s.

Factory MethodKey Features

Defines an interface for creating objects without needing to know each object’s type

Encapsulates the instantiation of concrete types

Leaves the details of instantiation to subclasses

Page 3: Factory Method A Creational Design Pattern. Factory Method Key Features  Defines an interface for creating objects without needing to know each object’s.

Factory MethodUML

Page 4: Factory Method A Creational Design Pattern. Factory Method Key Features  Defines an interface for creating objects without needing to know each object’s.

Factory MethodDocument Example

abstract class DocumentFactory {

public abstract Document getDocument();

}

class HTMLCreator extends DocumentFactory {

public Document getDocument() {

return new HTMLDocument();

}

}

class XMLCreator extends DocumentFactory {

public Document getDocument() {

return new XMLDocument();

}

}

abstract class Document {

...

}

class HTMLDocument extends Document {

...

}

class XMLDocument extends Document {

...

}

Page 5: Factory Method A Creational Design Pattern. Factory Method Key Features  Defines an interface for creating objects without needing to know each object’s.

Factory MethodEncapsulation Example

class DocumentFactory {

public static Document getDocument(String file) {

int type = getType(file);

switch(type) {

case DocumentFactory.HTML:

return new HTMLDocument(file);

case DocumentFactory.XML:

return new XMLDocument(file);

...

}

}

Page 6: Factory Method A Creational Design Pattern. Factory Method Key Features  Defines an interface for creating objects without needing to know each object’s.

Factory MethodBenefits

Types of created objects can be determined at runtime

Common interface allows for easier use by client classes

Useful for toolkits and frameworks

Limitations

Might need to subclass the factory to create concrete things (e.g., need to create an HTMLCreator to create an HTMLDocument)