Logo F2FInterview

Patterns Interview Questions

Q   |   QA
‹‹ previous123456

A reusable software design solution in general for the problems that are recurrently occuring. Design pattern is not a solution but a description for how to solve a problem in different situations. OOP design patterns establishes the relationships between classes or objects. Design patterns are specifically dealt with problem solving at the software design level. 

Analysis pattern are targeted for domain architecture, where as design pattern are targeted for implementation mechanism for some of the aspects of the domain. Analysis patterns are functional oriented and of high level. 

It is a software pattern which is not related to a language. It is related to a business domain like health care, telecom. The visiting activity of a patient in the health care domain would be subject to a number of patterns. 

The following are the steps to write a thread-safe singleton:

  • Declare a Boolean variable, ‘instantiated’, to know the status of instantiation of a class, an object of Object class and a variable of the same class with initial value as null.
  • Write a private constructor of this class
  • Override getInstance() method. Check the Boolean state of the instance variable ‘instantiated’. If it is false, write a ‘synchronized’ block and test for the current class instance variable. If it is null create an object of the current class and assign it to the instance variable.

The following code illustrates this :

public class SampleSingleton {
private static boolean initialized = false;
private static Object obj = new Object();
private static SampleSingleton instance = null;
private SampleSingleton() {
// construct the singleton instance
}
public static SampleSingleton getInstance() {
if (!initialized) {
synchronized(obj) {
if (instance == null) {
instance = new SampleSingleton();
initialized = true;
}
}
}
return instance;
}
} 

Singleton pattern is one of the design patterns that is utilized for restricting instantiation of a class to one or few specific objects. This facility is particularly useful when the system requires to coordinate the actions with exactly one object.

‹‹ previous123456

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: