Posts

Showing posts from June, 2014

Immutable Class - Java

Class should be made final - avoiding overriding of methods by sub classes All fields should be final and private - avoiding fields access outside the class and avoiding the  changes in the field values No setters Make sure that mutable fields getters will return a defensive copy from their getter method, there by avoiding the state to be mutated public final class Immutable {     private final Integer immutableinteger;     private final String immutableString;     private final Date mutableDate;     public Immutable(Integer immutableinteger, String immutableString, Date mutableDate) {         this.immutableinteger = immutableinteger;         this.immutableString = immutableString;         this.mutableDate = mutableDate;     }     public Integer getImmutableinteger() {         return immutableinteger; ...

Singleton Class - Java

public class Singleton {     private static Singleton singleton;     //1. private prevents the instantiation of this object from other clesses     private Singleton(){     }     // 2. static word makes the method class level     // 3. synchronized avoids the multiple instantiation of object during multiple concurrent calls     public static synchronized Singleton getSingletonInstance(){         if(singleton == null){             singleton = new Singleton();         }         return singleton;     }     //4. avoiding cloning     public Object clone() throws CloneNotSupportedException{         return new CloneNotSupportedException();     } } public class SingletonDemo {     public static void main(String args[]){       ...