Open main menu

CDOT Wiki β

Changes

OpenOffice temporary template

2,747 bytes added, 02:41, 9 June 2010
Factory Pattern Design
=====Factory Pattern Design=====
=====Factory Pattern Design=====
 
OpenOffice.org development heavily uses the Factory Design Pattern.
 
Design patterns are conventional templates that describes how to solve common software problems. Since most developers are familiar with the patterns, they can recognize a pattern in others source code. That makes working in teams easier. There are many popular design patterns. One of them is Factory pattern.
 
Factory pattern is a type of creational pattern. Creational pattern pattern solves problems related to creating. Factory pattern solves two major problem generally faced by developers.
 
1. To reduce too many new operator usage
::When working on a large software, numerous instances of classes are created continuously at the runtime. The programmer cannot predict what the user is going to do. So at any given time, the programmer doesn't know what object is create. For example, To create a new document, the user might click new text document or new spreadsheet document. There would several possibilities about what the user is going to do. So, a factory class is assigned to do all these repetitive work of creating a new instance of what the user wants. By separating these repetitive object creations into a factory class, when new classes are added, only the factory class need to be updated.
 
2. To create object without knowing its class name.
::When using the concrete classes, the developer has to remember the class names. In factory pattern, choosing what type of object to be created is delegated to the factory class. Usually this is done by sending a parameter. Based on the parameter passed to the factory, the factory creates an instance of a certain type/class.
 
<pre>
 
public final class DocumentFactory {
 
XDocument document;
 
XDocument getDocument(String type){
 
if(type.equals("text"){
 
document = new TextDocument();
 
}
 
else if(type.equals("sheet"){
 
document = new SpreadSheet();
 
}
 
return document;
 
}
 
}
 
</pre>
 
<pre>
 
public interface XDocument{
 
open();
 
}
 
</pre>
 
<pre>
 
public class TextDocument implements XDocument{
 
//concrete class for Text documents
 
open(){
 
//method to open text document
 
System.out.println("opening a text document...");
 
}
 
}
 
</pre>
 
<pre>
 
public class SpreadSheet implements XDocument{
 
//concrete class for spreadsheet documents
 
open(){
 
//method to open spreadsheet document
 
System.out.println("opening a spreadsheet document...");
 
}
 
}
 
</pre>
 
<pre>
 
class DocumentProgram{
 
public static void main(String[] args){
 
XDocument doc = df.getDocument("text"); //this just created an instance of TextDocument without knowing its class name.
 
doc.open();
 
}
 
}
 
</pre>
=====Singletons=====
1
edit