Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials
  

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Tutorials
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Singleton Pattern

                         

Singleton Pattern: 

The singleton design pattern deals with one and only one instance of an object that encapsulates the control of the object from a common place. There are various ways of achieving this pattern.

For example, create an exception that is thrown by a class if the class is instantiated more than once. Next declare a boolean variable and  make it static so that it can be shared among all the instances of a class. Initialize this static variable inside the constructor of this class. The constructor would throw an exception if it is initialized second time. It is the best technique of using the singleton pattern. But take care to set the variable whenever destroying during the finalize method call.

Another approach of creating Singleton method includes a static method and private constructor in a class. Declaring the constructor as private ensures that the instance variable can be created only from inside the method of the class. The static method sets the variable as boolean that indicates the creation of the instance and returns an instance.

Benefits: Singleton pattern controls access to unique instances, reduce name space, permits a variable number of instances, allows refinement of operations and representations, and provides more flexibility than class operations.

Usage:  These are used in those places where there is only one instance of a class. The Singleton pattern is mostly used in multi-threaded applications. Singleton patterns are often used as global variables because the global variables permit allocation and initialization whenever required. They don't permit to pollute the global namespace with unnecessary variables.

package singleton;

import org.apache.log4j.Priority;

import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.io.FileOutputStream;
import java.util.Properties;
import java.io.PrintStream;
import java.io.InputStream;
import java.io.IOException;


public class Logger {
private String fileName;
private Properties properties;
private Priority priority;

private Logger() {
logger = this;
}

public int getRegisteredLevel() {
int i = 0;
try {
InputStream inputstream = getClass().getResourceAsStream("Logger.properties");
properties.load(inputstream);
inputstream.close();
i = Integer.parseInt(properties.getProperty("logger.registeredlevel"));
if(i < 0 || i > 3)
i = 0;
}
catch(Exception exception) {
System.out.println("Logger: Failed in the getRegisteredLevel method");
exception.printStackTrace();
}
return i;
}

private String getFileName(GregorianCalendar gc) {
SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MMM-yyyy");
String dateString = dateFormat1.format(gc.getTime());
String fileName = "C:\\prashant\\patterns\\log\\PatternsExceptionLog-" + dateString + ".txt";
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.

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

0 comments so far (post your own) View All Comments Latest 10 Comments:

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.