Tuesday, July 12, 2016

Design Patterns


READ
This section presents each pattern in its category:
·       Creational
·       Structural
·       Behavioral

Creational: Factory Method Pattern

Description: Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.
Components: Creator, Concrete Creator, Product
·       Creator: abstract definition the factory methods used to build the product
·       Concrete Creator: implementation of the creator
·       Product: final object being built
Factory method pattern that creates car engines based on your budget.
Listing 1. Engine.java
public interface Engine
{
  public int getSpeed();
  public void accelerate();
  public void decelerate();
}

Listing 2. StandardEngine.java

public class StandardEngine implements Engine {

Listing 3. TurboEngine.java

public class TurboEngine implements Engine {
Listing 4. EngineFactory.java
public class EngineFactory
{
  public static Engine getEngine( int budget )
  {
    if( budget >= 10000 )
    {
      return new TurboEngine();
    }
    return new StandardEngine();
  }
}

Example 2 :

interface Currency {
       String getSymbol();
}
class Rupee implements Currency {
       @Override
       public String getSymbol() {
              return "Rs";
       }
}
class CurrencyFactory {

       public static Currency createCurrency (String country) {
       if (country. equalsIgnoreCase ("India")){
              return new Rupee();
       }else if(country. equalsIgnoreCase ("Singapore")){
              return new SGDDollar();
       }else if(country. equalsIgnoreCase ("US")){
              return new USDollar();
        }
       throw new IllegalArgumentException("No such currency");
       }
}


Creational: Singleton Pattern

Description: Creates a single instance of a class for the entire JVM to share, which is good for stateless business objects or classes that represent specific pieces of physical hardware for which there is a one-to-one mapping of software objects to physical devices.
Components: Singleton object
·       Singleton object: there is one instance of each singleton object per JVM. Sometimes this object is initialized in a static code block and only accessible through a getInstance() method. The constructor for a singleton is usually private to stop anyone from creating any non-controlled instances of the class.
·       Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.
·        

Eager initialization

package com.journaldev.singleton;

public class EagerInitializedSingleton {
   
    private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
   
    //private constructor to avoid client applications to use constructor
    private EagerInitializedSingleton(){}

    public static EagerInitializedSingleton getInstance(){
        return instance;
    }
}

Lazy Initialization

package com.journaldev.singleton;

public class LazyInitializedSingleton {

    private static LazyInitializedSingleton instance;
   
    private LazyInitializedSingleton(){}
   
    public static LazyInitializedSingleton getInstance(){
        if(instance == null){
            instance = new LazyInitializedSingleton();
        }
        return instance;
    }
}

Thread Safe Singleton

Below code snippet provides the double checked locking implementation.
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    if(instance == null){
        synchronized (ThreadSafeSingleton.class) {
            if(instance == null){
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}

Enum Singleton

To overcome this situation with Reflection, Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. Since Java Enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.
package com.journaldev.singleton;

public enum EnumSingleton {

    INSTANCE;
   
    public static void doSomething(){
        //do something
    }
}

Builder pattern

The intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern[citation needed]. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.
public class User {
02
    private final String firstName; // required
03
    private final String lastName; // required
04
    private final int age; // optional
05
    private final String phone; // optional
06
    private final String address; // optional
07

08
    private User(UserBuilder builder) {
09
        this.firstName = builder.firstName;
10
        this.lastName = builder.lastName;
11
        this.age = builder.age;
12
        this.phone = builder.phone;
13
        this.address = builder.address;
14
    }
15

16
    public String getFirstName() {
17
        return firstName;
18
    }
19

20
    public String getLastName() {
21
        return lastName;
22
    }
23

24
    public int getAge() {
25
        return age;
26
    }
27

28
    public String getPhone() {
29
        return phone;
30
    }
31

32
    public String getAddress() {
33
        return address;
34
    }
35

36
    public static class UserBuilder {
37
        private final String firstName;
38
        private final String lastName;
39
        private int age;
40
        private String phone;
41
        private String address;
42

43
        public UserBuilder(String firstName, String lastName) {
44
            this.firstName = firstName;
45
            this.lastName = lastName;
46
        }
47

48
        public UserBuilder age(int age) {
49
            this.age = age;
50
            return this;
51
        }
52

53
        public UserBuilder phone(String phone) {
54
            this.phone = phone;
55
            return this;
56
        }
57

58
        public UserBuilder address(String address) {
59
            this.address = address;
60
            return this;
61
        }
62

63
        public User build() {
64
            return new User(this);
65
        }
66

67
    }
68
}

1
public User getUser() {

2
    return new

3
            User.UserBuilder('Jhon', 'Doe')

4
            .age(30)

5
            .phone('1234567')

6
            .address('Fake address 1234')

7
            .build();

8
}

Design Patterns - Composite Pattern

Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects.
This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of same objects.
import java.util.ArrayList;
import java.util.List;

public class Employee {
   private String name;
   private String dept;
   private int salary;
   private List<Employee> subordinates;

   // constructor
   public Employee(String name,String dept, int sal) {
      this.name = name;
      this.dept = dept;
      this.salary = sal;
      subordinates = new ArrayList<Employee>();
   }

   public void add(Employee e) {
      subordinates.add(e);
   }

   public void remove(Employee e) {
      subordinates.remove(e);
   }

   public List<Employee> getSubordinates(){
     return subordinates;
   }

   public String toString(){
      return ("Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary+" ]");
   }  
}

public class CompositePatternDemo {
   public static void main(String[] args) {
  
      Employee CEO = new Employee("John","CEO", 30000);

      Employee headSales = new Employee("Robert","Head Sales", 20000);

      Employee headMarketing = new Employee("Michel","Head Marketing", 20000);

      Employee clerk1 = new Employee("Laura","Marketing", 10000);
      Employee clerk2 = new Employee("Bob","Marketing", 10000);

      Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
      Employee salesExecutive2 = new Employee("Rob","Sales", 10000);

      CEO.add(headSales);
      CEO.add(headMarketing);

      headSales.add(salesExecutive1);
      headSales.add(salesExecutive2);

      headMarketing.add(clerk1);
      headMarketing.add(clerk2);

      //print all employees of the organization
      System.out.println(CEO);
     
      for (Employee headEmployee : CEO.getSubordinates()) {
         System.out.println(headEmployee);
        
         for (Employee employee : headEmployee.getSubordinates()) {
            System.out.println(employee);
         }
      }              
   }
}

Design Patterns - Facade Pattern

Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to existing system to hide its complexities.

Step 1

Create an interface.
Shape.java
public interface Shape {    void draw(); }

Step 2

Create concrete classes implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {     @Override    public void draw() {       System.out.println("Rectangle::draw()");    } }
Square.java
public class Square implements Shape {     @Override    public void draw() {       System.out.println("Square::draw()");    } }
Circle.java
public class Circle implements Shape {     @Override    public void draw() {       System.out.println("Circle::draw()");    } }

Step 3

Create a facade class.
ShapeMaker.java
public class ShapeMaker {    
private Shape circle;    
private Shape rectangle;    
private Shape square;     
public ShapeMaker() {       
circle = new Circle();       
rectangle = new Rectangle();       
square = new Square();    
}     
public void drawCircle(){       
circle.draw();    
}    
public void drawRectangle(){       
rectangle.draw();    }    
public void drawSquare(){       square.draw();    } 
}

Step 4

Use the facade to draw various types of shapes.
FacadePatternDemo.java
public class FacadePatternDemo {    
public static void main(String[] args) {      
 ShapeMaker shapeMaker = new ShapeMaker();        
shapeMaker.drawCircle();       
shapeMaker.drawRectangle();       
shapeMaker.drawSquare();                  } }

Step 5

Verify the output.
Circle::draw() Rectangle::draw() Square::draw()

Design Patterns - Proxy Pattern

In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.
In proxy pattern, we create object having original object to interface its functionality to outer world.

Implementation

We are going to create an Image interface and concrete classes implementing the Image interface. ProxyImage is a a proxy class to reduce memory footprint of RealImage object loading.
ProxyPatternDemo, our demo class, will use ProxyImage to get an Imageobject to load and display as it needs.
Description: roxy Pattern UML Diagram

Step 1

Create an interface.
Image.java
public interface Image {    void display(); }

Step 2

Create concrete classes implementing the same interface.
RealImage.java
public class RealImage implements Image {     private String fileName;     public RealImage(String fileName){       this.fileName = fileName;       loadFromDisk(fileName);    }     @Override    public void display() {       System.out.println("Displaying " + fileName);    }     private void loadFromDisk(String fileName){       System.out.println("Loading " + fileName);    } }
ProxyImage.java
public class ProxyImage implements Image{     private RealImage realImage;    private String fileName;     public ProxyImage(String fileName){       this.fileName = fileName;    }     @Override    public void display() {       if(realImage == null){          realImage = new RealImage(fileName);       }       realImage.display();    } }

Step 3

Use the ProxyImage to get object of RealImage class when required.
ProxyPatternDemo.java
public class ProxyPatternDemo {           public static void main(String[] args) {       Image image = new ProxyImage("test_10mb.jpg");        //image will be loaded from disk       image.display();        System.out.println("");              //image will not be loaded from disk       image.display();        } }

Step 4

Verify the output.
Loading test_10mb.jpg Displaying test_10mb.jpg  Displaying test_10mb.jpg

 Design Patterns - Observer Pattern

 

1.     interest rate change (subject) …update news paper, bank, credit union and etc (observer)
2.     New Auto policy (subject)…update house policy department and house security package (observer)  
2.

Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.

Implementation

Observer pattern uses three actor classes. Subject, Observer and Client. Subject is an object having methods to attach and detach observers to a client object. We have created an abstract class Observer and a concrete classSubject that is extending class Observer.
ObserverPatternDemo, our demo class, will use Subject and concrete class object to show observer pattern in action.
Description: bserver Pattern UML Diagram

Step 1

Create Subject class.
Subject.java
import java.util.ArrayList; import java.util.List;  public class Subject {      private List<Observer> observers = new ArrayList<Observer>();    private int state;     public int getState() {       return state;    }     public void setState(int state) {       this.state = state;       notifyAllObservers();    }     public void attach(Observer observer){       observers.add(observer);                  }     public void notifyAllObservers(){       for (Observer observer : observers) {          observer.update();       }    }   }

Step 2

Create Observer class.
Observer.java
public abstract class Observer {    protected Subject subject;    public abstract void update(); }

Step 3

Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{     public BinaryObserver(Subject subject){       this.subject = subject;       this.subject.attach(this);    }     @Override    public void update() {       System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) );     } }
OctalObserver.java
public class OctalObserver extends Observer{     public OctalObserver(Subject subject){       this.subject = subject;       this.subject.attach(this);    }     @Override    public void update() {      System.out.println( "Octal String: " + Integer.toOctalString( subject.getState() ) );     } }
HexaObserver.java
public class HexaObserver extends Observer{     public HexaObserver(Subject subject){       this.subject = subject;       this.subject.attach(this);    }     @Override    public void update() {       System.out.println( "Hex String: " + Integer.toHexString( subject.getState() ).toUpperCase() );     } }

Step 4

Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo {    public static void main(String[] args) {       Subject subject = new Subject();        new HexaObserver(subject);       new OctalObserver(subject);       new BinaryObserver(subject);        System.out.println("First state change: 15");          subject.setState(15);       System.out.println("Second state change: 10");         subject.setState(10);    } }

Step 5

Verify the output.
First state change: 15 Hex String: F Octal String: 17 Binary String: 1111 Second state change: 10 Hex String: A Octal String: 12 Binary String: 1010

Design Patterns - Strategy Pattern

In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

Implementation

We are going to create a Strategy interface defining an action and concrete strategy classes implementing the Strategy interface. Context is a class which uses a Strategy.
StrategyPatternDemo, our demo class, will use Context and strategy objects to demonstrate change in Context behaviour based on strategy it deploys or uses.
Description: trategy Pattern UML Diagram

Step 1

Create an interface.
Strategy.java
public interface Strategy {    public int doOperation(int num1, int num2); }

Step 2

Create concrete classes implementing the same interface.
OperationAdd.java
public class OperationAdd implements Strategy{    @Override    public int doOperation(int num1, int num2) {       return num1 + num2;    } }
OperationSubstract.java
public class OperationSubstract implements Strategy{    @Override    public int doOperation(int num1, int num2) {       return num1 - num2;    } }
OperationMultiply.java
public class OperationMultiply implements Strategy{    @Override    public int doOperation(int num1, int num2) {       return num1 * num2;    } }

Step 3

Create Context Class.
Context.java
public class Context {    
private Strategy strategy;     
public Context(Strategy strategy){       
this.strategy = strategy;    }     
public int executeStrategy(int num1, int num2){       
return strategy.doOperation(num1, num2);    } }

Step 4

Use the Context to see change in behaviour when it changes its Strategy.
StrategyPatternDemo.java
public class StrategyPatternDemo {    
public static void main(String[] args) {       
Context context = new Context(new OperationAdd());                  System.out.println("10 + 5 = " + context.executeStrategy(10, 5));        
context = new Context(new OperationSubstract());                    System.out.println("10 - 5 = " + context.executeStrategy(10, 5));        
context = new Context(new OperationMultiply());                     System.out.println("10 * 5 = " + context.executeStrategy(10, 5));    
} }

Step 5

Verify the output.
10 + 5 = 15 10 - 5 = 5 10 * 5 = 50

Top 10 Java design pattern interview question Answer

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

Design pattern interview question in Java
design pattern interview question are integral part of any good list of core Java interview questions. Java is a popular Object oriented programming language and have lots of design pattern and design principles, contributed by many developers and open source framework. As a Java programmer its expected from you to know OOPS concept like
AbstractionEncapsulation and polymorphism, What is design pattern in Java, Some popular Java design pattern and most importantly when to use those design pattern in Java application. purpose of asking design pattern interview question in Java is to check whether Java programmer are familiar to those essential design patterns or not. Design patterns in Java interviews are as important as multi-threadingcollection and programming questions. If you are senior or experienced Java programmer than expect more complex and tough design pattern in Java interview e.g. Chain of responsibility design pattern and solving real time software design questions.


What is Observer design pattern in Java? When do you use Observer pattern in Java?

This is one of the most common Java design pattern interview question. Observer pattern is based upon notification, there are two kinds of object Subject and Observer. Whenever there is change on subject's state observer will receive notification. See 
What is Observer design pattern in Java with real life example for more details.




What is decorator pattern in Java? Can you give an example of Decorator pattern?
Decorator pattern is another popular java design pattern question which is common because of its heavy usage in
java.io package. BufferedReader and BufferedWriter are good example of decorator pattern in Java. SeeHow to use Decorator pattern in Java fore more details.


What is Singleton pattern in Java? 
Singleton pattern in Java is a pattern which allows only one instance of Singleton class available in whole application. java.lang.Runtime is good example of Singleton pattern in Java. There are lot's of follow up questions on Singleton pattern see 
10 Java singleton interview question answers for those followups 


Volatile :



Can you write thread-safe Singleton in Java?
There are multiple ways to write thread-safe singleton in Java e.g by writing singleton using double checked locking, by using static Singleton instance initialized during 
class loading. By the way using Java enum to create thread-safe singleton is most simple way. See Why Enum singleton is better in Java for more details.

What is Factory pattern in Java? What is advantage of using static factory method to create object?
Factory pattern in Java is a creation Java design pattern and favorite on many Java interviews. Factory pattern used to create object by providing static factory methods. There are many advantage of providing factory methods e.g. caching immutable objects, easy to introduce new objects etc. See 
What is Factory pattern in Java and benefits for more details.


What is difference between Factory and Abstract factory in Java
see  
here of this Java interview question.


What is Builder design pattern in Java? When do you use Builder pattern ?
Builder pattern in Java is another creational design pattern in Java and often asked in Java interviews because of its specific use when you need to build an object which requires multiple properties some optional and some mandatory. See
When to use Builder pattern in Java for more details

Can you write code to implement producer consumer design pattern in Java?

Producer consumer design pattern is a concurrency design pattern in Java which can be implemented using multiple way. if you are working in Java 5 then its better to use Concurrency util to implement producer consumer pattern instead of plain old 
wait and notify in Java.  Here is a good example of implementing producer consumer problem using BlockingQueue in Java




What is difference between Abstraction and Encapsulation in Java?

I have already covered answer of this Java interview question in my previous post as 
Difference between encapsulation and abstraction in Java. See there to answer this question.


This was my list of 10 popular design pattern interview question in Java. I have not included MVC (Model View Controller) design pattern because that is more specific to J2EE and 
Servlet JSP interview, but if you are going for any Java interview which demands experience in J2EE than you must prepare MVC design pattern. That's all on Java design pattern interview question and answers. Please let us know if you have any other interesting question on Java design pattern.


Full DP explanation.



structural design pattern

Adapter ... wrap a legacy object that provides an incompatible interface with an object that supports the desired interface
its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter.
mobile charger as an adapter because mobile battery needs 3 volts to charge but the normal socket produces either 120V (US) or 240V (India)

Facade ... wrap a complicated subsystem with an object that provides a simple interface
Bank account type – savings account, current account,
Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to exiting system to hide its complexities.
This pattern involves a single class which provides simplified methods which are required by client and delegates calls to existing system classes methods.
We're going to create a Shape interface and concrete classes implementing the Shape interface. A facade class ShapeMaker is defined as a next step.

Proxy:

A Proxy can also be defined as a surrogate. In the real work a cheque or credit card is a proxy for what is in our bank account.  It can be used in place of cash, which is what is needed, and provides a means of accessing that cash when required. And that's exactly what the Proxy pattern does - controls and manage access to the object they are "protecting".



BEHAVIOUR
Strategy
Strategy ... define algorithm interface in a base class and implementations in derived classes

Strategy pattern is one of the behavioral design pattern. Strategy pattern is used when we have multiple algorithms for a specific task and client decides the actual implementation to be used at runtime.
payment strategies – using Credit Card or using PayPal.


Observer :
Whenever there is change on subject's state observer will receive notification

1.Credit Card/bank Account transaction –Txt Message – phone, email
2. New customer (Comcast/ Auto insurance)---- send notification to sales/marketing team to check if the customer is interested for cable(channels) / home insurance.

CREATIONAL:


Factory Method :
we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Shape interface and concrete classes implementing the Shape interface

Factory Method ... define "createInstance" placeholder in the base class, each derived class calls the "new" operator and returns an instance of itself
Bank account type – savings account, current account,

factory design pattern in java, you will notice that we have a single Factory class that returns the different sub-classes based on the input provided and factory class uses if-else or switch statement to achieve this.

Abstract Factory- Good






Full DP explanation.


Front Controller :

The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers



To make it simple, let us say that we can use constructor based dependency injection for mandatory dependencies and setter based injection for optional dependencies. It is a thumb of rule!!
Lets say for example.
If you want to instantiate a class you always do it with its constructor. So if you are using constructor based injection, the only way to instantiate the class is through that constructor. If you pass the dependency through constructor it becomes evident that it is a mandatory dependency.
On the other hand, if you have a setter method in a POJO class, you may or may not set value for your class variable using that setter method. It is completely based on your need. i.e. it is optional. So if you pass the dependency through setter method of a class it implicitly means that it is an optional dependency. Hope you are clear!!


10 interview question on Singleton Pattern in Java

Question starts with
What is Singleton class? Have you used Singleton before?

Singleton is a class which has only one instance in whole application and provides a
getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.

1) Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?
Here they will check whether candidate has enough experience on usage of singleton or not. Does he is familiar of advantage/disadvantage or alternatives available for singleton in Java or not.
Answer: Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision.

2) Can you write code for
getInstance() method of a Singleton class in Java?

Answer: Until asked don’t write code using double checked locking as it is more complex and chances of errors are more but if you have deep knowledge of double checked locking, volatile variable and lazy loading than this is your chance to shine. I have shared code examples of writing singleton classes using enum, using static factory and with double checked locking in my recent post Why Enum Singletons are better in Java, please see there.


3) Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer?
This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. read more about synchronization on How Synchronization works in JavaAnswer: This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to
getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton,  It’s better to only synchronize critical section and not whole method. Singleton pattern is also closely related to factory design pattern where getInstance() serves as static factory method.
4) What is lazy and early loading of Singleton and how will you implement it?
This is another great Singleton interview question in terms of understanding of concept of loading and cost associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to know concept.
Answer: As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.



5) Example of Singleton in standard Java Development Kit?
This is open question to all, please
share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime
Answer: There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:
  • Java.lang.Runtime with getRuntime() method
  • Java.awt.Toolkit with getDefaultToolkit()
  • Java.awt.Desktop with  getDesktop()

6) What is double checked locking in Singleton?
One of the most hyped question on Singleton pattern and really demands complete understanding to get it right because of Java Memory model caveat prior to Java 5. If a guy comes up with a solution of using volatile keyword with Singleton instance and explains it then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.
Answer: Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.

public Singleton getInstance(){

     
if(_INSTANCE == null){
       
synchronized(Singleton.class){
       
//double checked locking - because second check of Singleton instance with lock
               
if(_INSTANCE == null){
                    _INSTANCE =
new Singleton();
               
}
           
}
       
}
   
return _INSTANCE;
}

Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.

7) How do you prevent for creating another instance of Singleton using
clone() method?This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java.Answer: Preferred way is not to implement
Clonnable interface as why should one wants to create clone() of Singleto and if you do just throw Exception from clone() method as  “Can not create clone of Singleton class”.
8) How do you prevent for creating another instance of Singleton using reflection?
Open to all. In my opinion throwing exception from constructor is an option.
Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”
9) How do you prevent for creating another instance of Singleton during serialization?
Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you.Answer: You can prevent this by using
readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance.  I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranted of that.
10) When is Singleton not a Singleton in Java?
There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible. Here is the link of that article http://java.sun.com/developer/technicalArticles/Programming/singletons/

Apart from these questions on Singleton pattern, some of my reader contributer few more questions, which I included here. Thank you guys for your contribution.

11) Why you should avoid the singleton anti-pattern at all and replace it with DI?
Answer: Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.
Description: Singleton pattern interview questions answers in JavaSingleton Anti-Pattern: with more and more classes calling getInstance the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once).

12) How many ways you can write Singleton Class in Java?

Answer:  I know atleast four ways to implement Singleton pattern in Java
1) Singleton by synchronizing
getInstance() method2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums

13) How to write thread-safe Singleton in Java?
Answer: Thread-Saffe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by classloader.

At last few more questions for your practice, contributed by Mansi:
14) Singleton vs Static Class?
15) When to choose Singleton over Static Class?
16) Can you replace Singleton with Static Class in Java?
17) Difference between Singleton and Static Class in java?
18) Advantage of Singleton over Static Class?

Observer design pattern in Java is a fundamental core Java pattern where Observe watch for any change in state or property of Subject. For Example Company updates all its shareholders for any decision they make here Company is Subject and Shareholders are Observers, any change in policy of company and Company notifies all its Shareholders or Observer. This was simple real world explanation of Observer pattern. In this article we will in detail what is Observer Design pattern, what is benefit of Observer design Pattern, Example or Observer pattern in Java and few other points. Just like Decorator design Pattern andFactory Pattern in Java, Observer pattern is also used in JDK.

Observer design Pattern Java Code Example

What is Observer design Pattern?

Description: Observer design pattern in Java Code ExampleObserver design pattern in Java is very important pattern and as name suggest it’s used to observe things. Suppose you want to notify for change in a particular object than you observer that object and changes are notified to you. Object which is being observed is refereed as Subject and classes which observe subject are called Observer. This is beautiful pattern and used heavily along with Model View Controller Design pattern where change in model is propagated to view so that it can render it with modified information. Observer pattern is also a very popular Java interview questions and mostly asked on Senior or mid senior level.

Example – New Lease (rent) – Insurance, Cable, Internet, Phone and etc..

Problem which is solved by Observer Pattern:


If we have requirement that if particular object change its state and on depending upon
This changes some or group of objects automatically change their state we need to implement observer pattern it will reduce coupling between objects.
In real world if try to find example see when we subscribe for New Phone connection whenever customer is registered with that company all other departments are notified accordingly and then depending upon the state the do their jobs like do the verification of their address then if customer state is verified then dispatch the welcome kit etc.



How Observer Design Pattern is implemented in Java;


For implementation of this pattern java makes our task very easy, developer need not to do so much for implementing this pattern .In java.util package we can find interfaces ,classes and methods for implementing this pattern.

Public Interface Observer:

Any class who implements this interface must be notified when subject or observable object change its status.

Update (Observable Ob, Object arg): This method is called when subject is changed.


Class Observable:
It’s a subject to whom observer wants to observe.


Some Important Method:
addObserver(Observer o):add Observers in the set of observers for this subject or observalbel object.

deleteObserver(Observer o): delete Observers in the set of observers .

hasChanged():check if object has changed.

clearChanged():this method will indicate that subject has no changes or all the observers has been notified when changes is made.

notifyObservers(): notify all the observers if object has changed .


Read more:
 http://javarevisited.blogspot.com/2011/12/observer-design-pattern-java-example.html#ixzz2C0OqfwmH


What is decorator design pattern in Java?


·          Decorator design pattern is used to enhance the functionality of a particular object at run-time or dynamically.
·          At the same time other instance of same class will not be affected by this so individual object gets the new behavior.
·          Basically we wrap the original object through decorator object.
·          Decorator design pattern is based on abstract classes and we derive concrete implementation from that classes,
·          It’s a structural design pattern and most widely used.
When to use Decorator pattern in Java

·          When sub classing is become impractical and we need large number of different possibilities to make independent object or we can say we have number of combination for an object.

·          Secondly when we want to add functionality to individual object not to all object at run-time we use decorator design pattern.


Example –
Currency class

Based on the locale we can provide/add functionality
Advantage of Decorator design Pattern in Java

In brief we see what the main advantages of using decorator design patterns are.
1.      Decorator Pattern is flexible than inheritance because inheritance add responsibilities at compile time and it will add at run-time.
2.      Decorator pattern enhance or modify the object functionality


Disadvantage

Main disadvantage of using Decorator Pattern in Java is that the code maintenance can be a problem as it provides a lot of similar kind of small objects (each decorator).

if anyone wants to add some functionality to individual object or change the state of particular object at run time it is possible only by decorator pattern

Factory Method Design Pattern

05/11/2009
A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.
Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

Sample factory method design pattern implementation in Java API

For a reference of how the factory method design pattern is implemented in Java, you can have a look at SAXParserFactory. It is a factory class which can be used to intantiate SAX based parsers to pares XML. The method newInstance is the factory method which instantiates the sax parsers based on some predefined logic.

Block diagram for The Design Pattern

Description: factorydesignpattern

Sample Java Source Code for Factory Method Design Pattern

Based on comments received from users, I try to keep my sample java source code as simple as possible for a novice to understand.
Base class:
package com.javapapers.sample.designpattern.factorymethod;

//super class that serves as type to be instantiated for factory method pattern
public interface Pet {

 public String speak();

}
First subclass:
package com.javapapers.sample.designpattern.factorymethod;

//sub class 1 that might get instantiated by a factory method pattern
public class Dog implements Pet {

 public String speak() {
 return "Bark bark...";
 }
}
Ads by Google

Second subclass:
package com.javapapers.sample.designpattern.factorymethod;

//sub class 2 that might get instantiated by a factory method pattern
public class Duck implements Pet {
 public String speak() {
 return "Quack quack...";
 }
}
Factory class:
package com.javapapers.sample.designpattern.factorymethod;

//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {

 public Pet getPet(String petType) {
 Pet pet = null;

 // based on logic factory instantiates an object
 if ("bark".equals(petType))
 pet = new Dog();
 else if ("quack".equals(petType))
 pet = new Duck();
 return pet;
 }
}
Using the factory method to instantiate
package com.javapapers.sample.designpattern.factorymethod;

//using the factory method pattern
public class SampleFactoryMethod {

 public static void main(String args[]){

 //creating the factory
 PetFactory petFactory = new PetFactory();

 //factory instantiates an object
 Pet pet = petFactory.getPet("bark");

 //you don't know which object factory created
 System.out.println(pet.speak());
 }

}

Output of the above sample program for Factory Method Pattern

Bark bark



Factory Design pattern is based on
Encapsulation object oriented concept. Factory design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class.

examples of factory method design pattern from JDK is :
valueOf() method which returns object created by factory equivalent to value of parameter passed.
getInstance() method which creates instance of Singleton class.
newInstance() method which is used to create and return new instance from factory method every time called

When to use Factory design pattern in Java

  • Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework.        
  • Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
  • Factory method is used when Products don't need to know how they are created.
  • We  can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided

Here is complete code example of Factory pattern in Java:

interface Currency {
       String getSymbol();
}
// Concrete Rupee Class code
class Rupee implements Currency {
       @Override
       public String getSymbol() {
              return "Rs";
       }
}

// Concrete SGD class Code
class SGDDollar implements Currency {
       @Override
       public String getSymbol() {
              return "SGD";
       }
}

Example - Logger – Console in development box or log file/ db in qa/production or

Advantage of Factory method Pattern in Java:

Factory pattern in Java is heavily used everywhere including JDK, open source library and other frameworks.In following are main advantages of using Factory pattern in Java:

1) Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code?
E.g.: JDBC is a good example for this pattern; application code doesn't need to know what database it will be used with, so it doesn't know what database-specific driver classes it should use. Instead, it uses factory methods to get Connections, Statements, and other objects to work with. Which gives you flexibility to change your back-end database without changing your DAO layer in case you are using ANSI SQL features and not coded on DBMS specific feature?

2) Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory.

3) Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side.

4) Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.

Some more advantages of factory method design pattern is:
1. Static factory method used in factory design pattern enforces use of Interface than implementation which itself a good practice. for example:

Map synchronizedMap = Collections.synchronizedMap(new HashMap());

2. Since static factory method have return type as Interface, it allows you to replace implementation with better performance version in newer release.
3. Another advantage of static factory method pattern is that they can cache frequently used object and eliminate duplicate object creation. Boolean.valueOf() method is good example which caches true and false boolean value.
5 Factory method pattern offers alternative way of creating object.
6. Factory pattern can also be used to hide information related to creation of object.

Abstract Factory Design Pattern

11/11/2009
Factory of factories. To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need not be aware of the final concrete class that will be instantiated. You can program for the interface using the top factory.
There is also a view that abstract factory is ‘also’ implemented using prototype instead of factory methords pattern. Beginners for now please don’t yourself with that. Just go with factory methods pattern.
As there is a word ‘abstract’ in the pattern name don’t mistake and confuse it with java ‘abstract’ keyword. It is not related to that. This abstract is from object oriented programming paradim.

Sample abstract factory design pattern implementation in Java API

XML API implements abstract factory. There is a class nameSchemaFactory. This acts as a factory and supports implemenation of multiple schemas using abstract factory design pattern.

Sample Java Source Code for Factory Method Design Pattern

Following is the interface, that will be returned as the final end product from the factories.
package com.javapapers.sample.designpattern.abstractfactory;

public interface Animal {
  public void breathe();
}
Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.
package com.javapapers.sample.designpattern.abstractfactory;

public interface AnimalFactory {
  public Animal createAnimal();
}
One of the factory from a predefined set which will instantiate the above interface.
package com.javapapers.sample.designpattern.abstractfactory;

public class SeaFactory implements AnimalFactory {

  public Animal createAnimal() {
    return new Shark();
  }

}
Second factory from a predefined set which will instantiate the Animal interface.
package com.javapapers.sample.designpattern.abstractfactory;

public class LandFactory implements AnimalFactory {
  public Animal createAnimal() {
    return new Elephant();
  }
}
Ads by Google

Implementation of an Animal. This class is grouped with the first abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;

public class Shark implements Animal {
  public void breathe() {
    System.out.println("I breathe in water! He he!");
  }
}
Implementation of an Animal. This class is grouped with the second abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;

public class Elephant implements Animal {
  public void breathe() {
    System.out.println("I breathe with my lungs. Its easy!");
  }
}
Following class consumes the abstract factory.
package com.javapapers.sample.designpattern.abstractfactory;

public class Wonderland {
  public Wonderland(AnimalFactory factory) {
    Animal animal = factory.createAnimal();
    animal.breathe();
  }
}
Testing the abstract factory design pattern.
package com.javapapers.sample.designpattern.abstractfactory;

public class SampleAbstractFactory {

  public static void main(String args[]){
    new Wonderland(createAnimalFactory("water"));
  }

  public static AnimalFactory createAnimalFactory(String type){
    if("water".equals(type))
      return new SeaFactory();
    else
      return new LandFactory();
  }
}

Output of the above sample program for abstract factory pattern

I breathe in water! He he!

Singleton Design Pattern

02/05/2011
Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!
Description: http://javapapers.com/wp-content/uploads/2011/04/singleegg.jpg
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.
There are only two points in the definition of a singleton design pattern,
1.   there should be only one instance allowed for a class and
2.   we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]“.
The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.
Ads by Google

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton instance.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }
You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
This article is an attempt to explain the basics on singleton design pattern. If you want more insight on singleton refer this technical article “When is a Singleton not a Singleton?” and its references.

Usage of Singleton Pattern in Java API

java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()







.




Both Abstract Factory and Factory design pattern are creational design pattern and use to decouple clients from creating object they need, But there is a significant difference between Factory and Abstract Factory design pattern, Factory design pattern produces implementation of Products e.g. Garment Factory produce different kinds of clothes, On the other hand Abstract Factory design pattern adds another layer of abstraction over Factory Pattern and Abstract Factory implementation itself e.g. Abstract Factory will allow you to choose a particular Factory implementation based upon need which will then produce different kinds of products.

In short
1) Abstract Factory design pattern  creates Factory
2) Factory design pattern creates Products

Difference between Abstract Factory and Factory design pattern in Java

Description: Difference between Factory vs Abstract Factory pattern in JavaLet see another example of Abstract Factory and Factory design pattern in Java from JDK itself to get a better understanding. If you have done some XML work in Java e.g. reading XML files using DOM parser, you may be familiar with DocumentBuilderFactory  class which is an example abstract factory design pattern because it returns a factory called DocumentBuilder which then used to create Document.

//Example of Abstract Factory and Factory design pattern  in Java
DocumentBuilderFactory abstractFactory = DocumentBuilderFactory.
newInstance();
DocumentBuilder factory = abstractFactory.
newDocumentBuilder();
Document doc = factory.
parse(stocks)

In this example DocumentBuilderFactory (Abstract Factory) creates DocumentBuilder (Factory) which creates Documents (Products).

Let's see some more difference between Abstract Factory and Factory design pattern in Java in point form :

1) One more difference between Abstract Factory and Factory design pattern is that AbstractFactory pattern uses composition to delegate responsibility of creating object to another class while Factory design pattern uses inheritance and relies on derived class or sub class to create object.

2) Abstract Factory may use Factory design pattern for creating objects but they are not just limited to that they can also use Builder design pattern to build object by doing series of steps or Prototype pattern to build object by copying or customizing prototype of that object. It completely depends upon your implementation whether to use Factory pattern or Builder pattern for creating products.


When to use Abstract Factory and Factory method design pattern in Java
Factory method design pattern are modern way of creating objects. It offers some notable advantages over new() operator to create Objects e.g. By using Factory method design pattern client is completely decoupled with object creation code, which enforces Encapsulation and result is loosely coupled and highly cohesive system. Any change e.g. a new product from Factory requires almost no change in existing clients. See When to use Factory method design pattern in Java for more scenarios. On the other hand if you need an additional level of abstraction over your Factory pattern than Abstract Factory is the right design pattern to use. Abstract Factory allows you to use different Factory implementation for different purpose. Abstract Factory pattern can be implemented using Factory method and Singleton design pattern in Java. One of the best example of Abstract Factory and Factory pattern in Java is DocumentBuilderFactory and DocumentBuilder javax.xml.parsers package.


That's all on difference between Abstract Factory and Factory design pattern in Java. In short Abstract Factory design pattern provides abstraction over Factory pattern itself while Factory design pattern provides abstraction over products.