Magazine
 

Creational Design Patterns

return fileName;
}
public void logMsg(Priority p, String message) {
try {
GregorianCalendar gc = new GregorianCalendar();
String fileName = getFileName(gc); FileOutputStream fos = new FileOutputStream(fileName, true); PrintStream ps = new PrintStream(fos); SimpleDateFormat dateFormat2 = new SimpleDateFormat("EEE, MMM d, yyyy 'at' hh:mm:ss a"); ps.println("<"+dateFormat2.format (gc.getTime())+">["+message+"]"); ps.close();
}
catch (IOException ie) { ie.printStackTrace();
}}
public static void initialize() {
logger = new Logger();
}
// singleton - pattern
private static Logger logger;
public static Logger getLogger() { return logger;
}}

Difference between static class and static method approaches: One question that comes to most of the people's mind is that" What’s the difference between a static class and a singleton class?" The answer is static class is one of the approaches that makes a class “Singleton”. We can create and declare a class as “final” simply by declaring all its methods as “static”. In this case, you can call the static methods directly but can’t create any instance of class.
 

Example:

final class Logger {
//implementation of a static class of a
Singleton pattern
static public void logMessage(String s) {
System.out.println(s);
}}
public class StaticLogger {
public static void main(String args[]) {
Logger.logMessage("This is SINGLETON");
}}

The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.

Builder Pattern:

This design pattern allows the client to construct a complex object based on its type and content. One can achieve the way of constructing the objects by using the factory pattern. This is similar to the abstract factory pattern as both returns a group of related objects. The only difference between these two patterns is that Builder pattern makes a complex object step by step on the basis of data passed to it.

Benefits: These types of patterns provide greater control over construction process, separation between the construction and representation, and support to change the internal representation of objects.

Usage: Builder is useful in those conditions where you need to assemble several different kinds of complex objects at runtime. Once it is created it isolates the building process of object, from the object itself. Different objects may be constructed by using similar methods but once the

Sept 2007 | Java Jazz Up | 45
 
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   Download PDF