Posts

Showing posts with the label staic class

Lazy initializing your code

Many time we have static fields in our Java classes. These fields are get initialized with loading of your classes and all other static fields. But many time its not the urgent to initialize few of the fields while loading the class itself. Here the concept of lazy initialization comes in picture. Consider the code below public class LazyInitilaizationTest { public static String[] field = getStringContent(); static { System.out.println( "Loading Class" ); } public static String[] getStringContent(){ System.out.println( "Initializing field" ); return new String[]{}; } public static void main(String[] args) { System.out.println( "Accessing Field" ); System.out.println(field); } } Here the class has private & static field which gets initialized by invoking getStringContent () method. Running above class prints following output Initializing field Loading Class Acce...

Alternative implementation for Singleton Class

In previous posts on Singleton Designing pattern I have explained one of the way of implementing and solving concurrency issue. Singleton pattern insures that only one instance of the class should be available throughout the application context. There is an alternative implementation for insuring the same functionality that is nothing but “a class with all public static methods” . A static method can be accessed directly by Class name without any class instance. It will serve same purpose as Singleton Class, means it shares only one state across the application. Here is a sample implementation import java.util.*; class SingletonMap { private static Map<String,String> map; static { map = new HashMap<String,String>(); } public static String getValue(String key){ return map.get(key); } public static void putValue(String key, String value){ map.put(key,value); } } Here the SingletonMap class with all methods declared as “static” and private stati...

Singleton Vs Static Class

"Singleton designing pattern deals with a pattern in which instantiation of object is under control and restrict count by one by making constructor as private " "A Static mean a class that has only static members" A Singleton class is supposed to have one and only one instance while a static class is never instantiated . The singleton pattern has several advantage over the static class pattern A Singleton can extend class and implement interfaces, while a static class can not. A singleton can be initiated lazily or asynchronously while a static class is generally initialized when it is first loaded A singleton class can be extended and its methods overridden , We can not override static methods with non static method