Infinitude Zone
Knowledge Sharing blog for you...
Read On

Factory Method Design Pattern

Saturday, June 05, 2010


Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass specifies all standard and generic behavior (using pure virtual “placeholders” for creation steps), and then delegates the creation details to subclasses that are supplied by the client.


Factory Method makes a design more customizable and only a little more complicated. Other design patterns require new classes, whereas Factory Method only requires a new operation.


People often use Factory Method as the standard way to create objects; but it isn’t necessary if: the class that’s instantiated never changes, or instantiation takes place in an operation that subclasses can easily override (such as an initialization operation).


Factory Method is similar to Abstract Factory but without the emphasis on families.


Factory Methods are routinely specified by an architectural framework, and then implemented by the user of the framework.




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.


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
   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();
   }    
}
//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.
Read On

Type of Design Patterns

Saturday, June 05, 2010
Creational design patterns

This design patterns is all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done.




Abstract Factory
Creates an instance of several families of classes
Builder
Separates object construction from its representation
Factory Method
Creates an instance of several derived classes
Object Pool
Avoid expensive acquisition and release of resources by recycling objects that are no longer in use
Prototype
A fully initialized instance to be copied or cloned
Singleton
A class of which only a single instance can exist


Structural design patterns

This design patterns is all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality.




Adapter
Match interfaces of different classes
Bridge
Separates an object’s interface from its implementation
Composite
A tree structure of simple and composite objects
Decorator
Add responsibilities to objects dynamically
Facade
A single class that represents an entire subsystem
Flyweight
A fine-grained instance used for efficient sharing
Private Class Data
Restricts accessor/mutator access
Proxy
An object representing another object


Behavioral design patterns

This design patterns is all about Class's objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects.




Chain of responsibility
A way of passing a request between a chain of objects
Command
Encapsulate a command request as an object
Interpreter
A way to include language elements in a program
Iterator
Sequentially access the elements of a collection
Mediator
Defines simplified communication between classes
Memento
Capture and restore an object's internal state
Null Object
Designed to act as a default value of an object
Observer
A way of notifying change to a number of classes
State
Alter an object's behavior when its state changes
Strategy
Encapsulates an algorithm inside a class
Template method
Defer the exact steps of an algorithm to a subclass
Visitor
Defines a new operation to a class without change


I will explain above patterns one by one later..... KIT

Cheers
Read On

What is Design Pattern.?

Saturday, June 05, 2010

Usage of Design Patterns

Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.
Often, people only understand how to apply certain software design techniques to certain problems. These techniques are difficult to apply to a broader range of problems. Design patterns provide general solutions, documented in a format that doesn't require specifics tied to a particular problem.
In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs.
Read On

FreeLancer.com

Find more freelance jobs

Blog Archive

Followers