The document discusses the Factory Method design pattern. It begins by defining Factory Method as defining an interface for creating objects but allowing subclasses to determine which class to instantiate. It then provides the class diagram and participants. The creator declares the factory method and subclasses override it to return the appropriate concrete product. The benefits are eliminating hardcoding of classes and enabling subclasses to customize object creation. Usage examples include not knowing object classes ahead of time and delegating responsibility to subclasses. The summary concludes by describing a code example of a Painting class using factory methods to return different Shape objects depending on the drawing condition.
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
242 views
Factory Method Design Pattern
The document discusses the Factory Method design pattern. It begins by defining Factory Method as defining an interface for creating objects but allowing subclasses to determine which class to instantiate. It then provides the class diagram and participants. The creator declares the factory method and subclasses override it to return the appropriate concrete product. The benefits are eliminating hardcoding of classes and enabling subclasses to customize object creation. Usage examples include not knowing object classes ahead of time and delegating responsibility to subclasses. The summary concludes by describing a code example of a Painting class using factory methods to return different Shape objects depending on the drawing condition.
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15
1
Factory Method Design Pattern, UML diagram,
Java Example Definition Class Diagram Participants Benefits Usage Example Definition Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Class Diagram
Factory Method pattern is a simplified version of Abstract Factory pattern. Factory Method pattern is responsible of creating products that belong to one family, while Abstract Factory pattern deals with multiple families of products. The official GoF Factory Method UML diagram (above) can be represented as in diagram below which uses the same terminology as Abstract Factory UML diagram: 2
Participants Product o defines the interface of objects the factory method creates. ConcreteProduct o implements the Product interface. Creator o declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. o may call the factory method to create a Product object. ConcreteCreator o overrides the factory method to return an instance of a ConcreteProduct Benefits Eliminates the needs to bind application classes into your code. The code deals woth interfaces so it can work with any classes that implement a certain interface. Enables the subclasses to provide an extended version of an object, because creating an object inside a class is more flexible than creating an object directly in the client. Usage When a class cannot anticipate the class of objects it must create. When a class wants its subclasses to specify the objects it creates. Classes delegate responsability to one of several helper subclasses, and you want to localize the knowledge of which helper subclasses is the delegate.
3
(II) Factory Method
Definition Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given. Where to use & benefits Connect parallel class hierarchies. A class wants its subclasses to specify the object. A class cannot anticipate its subclasses, which must be created. A family of objects needs to be separated by using shared interface. The code needs to deal with interface, not implemented classes. Hide concrete classes from the client. Factory methods can be parameterized. The returned object may be either abstract or concrete object. Providing hooks for subclasses is more flexible than creating objects directly. Follow naming conventions to help other developers to recognize the code structure. Related patterns include o Abstract Factory , which is a layer higher than a factory method. o Template method, which defines a skeleton of an algorithm to defer some steps to subclasses or avoid subclasses o Prototype, which creates a new object by copying an instance, so it reduces subclasses. o Singleton, which makes a returned factory method unique. Examples To illustrate such concept, let's use a simple example. To paint a picture, you may need several steps. A shape is an interface. Several implementing classes may be designed in the following way. interface Shape { public void draw(); } class Line implements Shape { Point x, y; Line(Point a, Point b) { x = a; 4 y = b; } public void draw() { //draw a line; } } class Square implements Shape { Point start; int width, height; Square(Point s, int w, int h) { start = s; width = w; height = h; } public void draw() { //draw a square; } } class Circle implements Shape { .... }
class Painting { Point x, y; int width, height, radius; Painting(Point a, Point b, int w, int h, int r) { x = a; y = b; width = w; height = h; radius = r; } Shape drawLine() { return new Line(x,y); } Shape drawSquare() { return new Square(x, width, height); } Shape drawCircle() { return new Circle(x, radius); } .... }
... Shape pic; Painting pt; //initializing pt .... if (line) pic = pt.drawLine(); if (square) pic = pt.drawSquare(); if (circle) pic = pt.drawCircle();
5 From the above example, you may see that the Shape pic's type depends on the condition given. The variable pic may be a line or square or a circle.
You may use several constructors with different parameters to instantiate the object you want. It is another way to design with Factory pattern. For example, class Painting { ... Painting(Point a, Point b) { new Line(a, b); //draw a line } Painting(Point a, int w, int h) { new Square(a, w, h); //draw a square } Painting(Point a, int r){ new Circle(a, r); //draw a circle } ... } You may use several methods to finish the drawing jobs. It is so-called factory method pattern. for example, class Painting { ... Painting(Point a, Point b) { draw(a, b); //draw a line } Painting(Point a, int w, int h) { draw(a, w, h); //draw a square } Painting(Point a, int r){ draw(a, r); //draw a circle } ... } The above draw() methods are overloaded.
Here is a popular example of Factory design pattern. For example, you have several database storages located in several places. The program working on the database is the same. The user may choose local mode or remote mode. The condition is the choice by the user. You may design your program with Factory pattern. When the local mode is set, you may instantiate an object to work on the local database. If the remote mode is set, you may instantiate an object which may have more job to do like remote connection, downloading, etc. 6 interface DatabaseService { public DataInfo getDataInfo() throws Exception; public FieldInfo getFieldInfo() throws Exception; public void write(FieldInfo fi) throws Exception; public void modify(FieldInfo fi) throws Exception; public void delete(FieldInfo fi) throws Exception; //... } class Data implements DatabaseService {
public Data(String fileName) {...}; public Data(URL url, String fileName) {....}; public DataInfo getDataInfo() throws Exception {...}; public FieldInfo getFieldInfo() throws Exception {...}; public void write(FieldInfo fi) throws Exception {...}; public void modify(FieldInfo fi) throws Exception {...}; public void delete(FieldInfo fi) throws Exception {...}; //.... } class DataManager{ Data data = null; ... if (local) { data = new Data(localFile); ... } if (remote){ data = new Data(connectRemote, databaseFile); ... } data.write(someInfo); data.modify(someInfo); .... }
To illustrate how to use factory design pattern with class level implementation, here is a real world example. A company has a website to display testing result from a plain text file. Recently, the company purchased a new machine which produces a binary data file, another new machine on the way, it is possible that one will produce different data file. How to write a system to deal with such change. The website just needs data to display. Your job is to provide the specified data format for the website. Here comes a solution. Use an interface type to converge the different data file format. The following is a skeleton of implementation. //Let's say the interface is Display interface Display {
//load a file public void load(String fileName);
//parse the file and make a consistent data type 7 public void formatConsistency();
}
//deal with plain text file class CSVFile implements Display{
public void load(String textfile) { System.out.println("load from a txt file"); } public void formatConsistency() { System.out.println("txt file format changed"); } }
//deal with XML format file class XMLFile implements Display {
public void load(String xmlfile) { System.out.println("load from an xml file"); } public void formatConsistency() { System.out.println("xml file format changed"); } }
//deal with binary format file class DBFile implements Display {
public void load(String dbfile) { System.out.println("load from a db file"); } public void formatConsistency() { System.out.println("db file format changed"); } }
//Test the functionality class TestFactory {
public static void main(String[] args) { Display display = null;
//use a command line data as a trigger if (args[0].equals("1")) display = new CSVFile(); else if (args[0].equals("2")) display = new XMLFile(); else if (args[0].equals("3")) display = new DBFile(); else System.exit(1);
//converging code follows display.load(""); display.formatConsistency(); } 8 } //after compilation and run it
C:\>java TestFactory 1 load from a txt file txt file format changed
C:\>java TestFactory 2 load from an xml file xml file format changed
C:\>java TestFactory 3 load from a db file db file format changed
In the future, the company may add more data file with different format, a programmer just adds a new class in accordingly. Such design saves a lot of code and is easy to maintain. Return to top
(III) Factory Method
/wEPDwUKLTk5N
home courses schedule registration careers contact us sitemap about us login design patterns pattern design patterns C#, WPF, ASP.NET, AJAX, PATTERNS Factory Method Design Pattern < back to list of patterns
definition UML diagram participants sample code in C#
definition
Define an interface for creating an object,
Better Code Better Career Better Lifestyle
Design Pattern Framework 2.0 TM
9 framework ajax design patterns wpf design patterns resources training and educatio n for professio nal develope rs but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Frequency of use: high return to top UML class diagram
return to top participants The classes and/or objects participating in this pattern are: Product (Page) o defines the interface of objects the factory method creates ConcreteProduct (SkillsPage, EducationPage, ExperiencePage) o implements the Product interface Creator (Document) o declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. o may call the factory method to create a Product object. ConcreteCreator (Report, Resume) o overrides the factory method to return an instance of a ConcreteProduct.
In C# and VB.NET
Click here for details
-- Instant Access -- Instant Download
10 return to top sample code in C# This structural code demonstrates the Factory method offering great flexibility in creating different objects. The Abstract class may provide a default object, but each subclass can instantiate an extended version of the object. Hide code // Factory Method pattern -- Structural example
class MainApp { static void Main() { // An array of creators Creator[] creators = new Creator[2]; creators[0] = new ConcreteCreatorA(); creators[1] = new ConcreteCreatorB();
// Iterate over creators and create products foreach(Creator creator in creators) { Product product = creator.FactoryMethod(); Console.WriteLine("Created {0}", product.GetType().Name); }
// Wait for user Console.Read(); } }
// "Product"
abstract class Product { }
// "ConcreteProductA" 11
class ConcreteProductA : Product { }
// "ConcreteProductB"
class ConcreteProductB : Product { }
// "Creator"
abstract class Creator { public abstract Product FactoryMethod(); }
// "ConcreteCreator"
class ConcreteCreatorA : Creator { public override Product FactoryMethod() { return new ConcreteProductA(); } }
// "ConcreteCreator"
class ConcreteCreatorB : Creator { public override Product FactoryMethod() { return new ConcreteProductB(); } } }
Output Created ConcreteProductA Created ConcreteProductB
This real-world code demonstrates the Factory method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the 12 Document class. Here, the Factory Method is called in the constructor of the Document base class. Hide code // Factory Method pattern -- Real World example