Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Thursday 29 August 2013

Top Most Builder Design pattern in Java - Example Tutorial

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java. 
Read more »

Tuesday 27 August 2013

Top Most How to create thread safe Singleton in Java - Java Singleton Example

Thread safe Singleton means a Singleton class which returns exactly same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton pattern ensures that exactly one instance of class will remain in Java program at any time. In our last post 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java. Prior to Java 5 double checked locking mechanism is used to create thread-safe singleton in Java which breaks if one Thread doesn't see instance created by other thread at same time and eventually you will end up with more than one instance of Singleton class. From Java 5 onwards volatile variable guarantee can be used to write thread safe singleton by using double checked locking pattern. I personally  don't prefer that way as there are many other simpler alternatives to write thread-safe singleton is available available like using static field to initialize Singleton instance or using Enum as Singleton in Java. Let’s see example of both ways to create thread-safe Singleton in Java.
Read more »

Friday 23 August 2013

Top Most Java Singleton Design Pattern


       Java has several design patterns Singleton Pattern being the most commonly used design pattern. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. 
    The Singleton class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the singleton object as it then makes this method a class level method that can be accessed without creating an object.
    One such scenario where it might prove useful is when we develop the Java Help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications. Since at any time we can do only with one main Help object and use the same object in different screens, Singleton Pattern suits best for its implementation.
    A singleton pattern can also be used to create a Connection Pool. If programmers create a new connection object in every java class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the Java application.

Implementing the Singleton Pattern

    To implement this design pattern we need to consider the following 4 steps:
Step 1: Provide a default Private constructor
public class SingletonObjectDemo
{
        //Note that the constructor is private
        private SingletonObjectDemo ()
        {
               // Optional Code
        }
}
 
Step 2: Create a Method for getting the reference to the Singleton Object
public class SingletonObjectDemo{
        private static SingletonObject singletonObject;
 
        //Note that the constructor is private
        private SingletonObjectDemo (){
               // Optional Code
        }
 
    public static SingletonObjectDemo getSingletonObject(){
      if (ref == null){
          singletonObject = new SingletonObjectDemo ();
       }
        return singletonObject;
 
    }
        
}
    We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.
Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized SingletonObjectDemo getSingletonObject()
    It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one singleton object being created. This could violate singleton pattern principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration
Step 4: Override the Object clone method to prevent cloning.
  We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
    This again violates the Singleton Design Pattern's objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.
public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException(); 
}
    The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class SingletonClass{
  
        private static SingletonClass singletonObject;
        
        /** A private Constructor prevents any other class from instantiating. */
        private SingletonClass(){
                 //     Optional Code
        }
        
        public static synchronized SingletonClass getSingletonObject()
        {
            if (singletonObject == null){
                singletonObject = new SingletonClass();
            }
            return singletonObject;
        }
        
        public Object clone()throws CloneNotSupportedException
        {
            throw new CloneNotSupportedException(); 
        }
                 
}
 
public class SingletonObjectDemo{
        public static void main(String args[]){
//             SingletonClass obj = new SingletonClass();   Compilation error not allowed
               
               //create the Singleton Object..
               SingletonClass obj = SingletonClass.getSingletonObject();
 
               // Your Business Logic
               System.out.println("Singleton object obtained");
               
        }
}
Another approach to using Singleton pattern

We don't need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing of singletons that may cause other problems.

public class SingletonClass {
        private static SingletonClass ourInstance = new SingletonClass(); 
        public static SingletonClass getInstance() { 
               return singletonObj; } 
        private SingletonClass() { 
        } 
}
 
    In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your Singleton class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the Singleton class when the application is running.

Wednesday 21 August 2013

Top Most String class Interview questions



·         It is final.
·         String objects are immutable.
Not methods of this class –append, delete, insert. Hence a code fragment like this causes compiler error ,
String s = “A”;
s.trim();s.append();//causes compiler error since append is not String method
·         “valueOf” is static method of String class.
·         String has many constructors ,some of the important ones take input parameters
Ø  string
Ø  stringBuffer
Ø  byte array
Ø  char array
Ø  Doesn’t take in any argument.
→ String constructor doesn’t take in parameter such as char, byte, int, short,
int array  ,any array other than char array and byte array etc .
·         String class has a method called length() where as array has attribute called ‘length’
hence, String s = “abcd”;
                        int a = s.length;//causes error
similarlay
                        int [] a = {1,2,3,4,5};
                        int b = a.length();//causes error
·         String s1  = new String(“abcd”);
String s2 = s1.toString();
here toString method returns the reference to the existing object hence
“s1==s2” will be true.
Note: Even substring(),trim(),concat(),return the same string if they don’t modify the given string.
·         String s1 = “santosh”;
String s2 = “santosh”;
then “s1==s2” is true ,since while creating a string object the compiler looks for the same String in the pool and if it finds one then it returns the reference to the existing string.
Note: given ,
      String s ,s1 ,s2,s3;
      s=s1=s2=s3=null;
      {….compelx code….}
      s=s1+s2;
      s3 = s1+s2;
      then “s == s3“ will return false.

Monday 19 August 2013

Thursday 15 August 2013

Top Most Inversion of Control and Dependency Injection design pattern with real world Example - Spring tutorial

Inversion of Control and Dependency Injection is a core design pattern of Spring framework. IOC and DI design pattern is also a popular design pattern interview question in Java.As name suggest Inversion of control pattern Inverts responsibility of managing life cycle of object e.g. creating object, setting there dependency etc from application to framework, which makes writing Java application even more easy. Programmer often confused between IOC and DI, well both words used interchangeably in Java world but Inversion of Control is more general concept and Dependency Injection is a concrete design pattern. Spring framework provides two implementation of IOC container in form of Application Context and BeanFactorywhich manages life-cycle of bean used by Java application. As you may know necessity is mother of invention, it benefit to first understand problem solved by IOC and Dependency Injection design pattern. This makes your understanding more clear and concrete. We have touched basics of Dependency Injection and Inversion of control in our article 10 OOPS and SOLID design principles for Java programmer and this Java article tries to explain it by taking a real life example of Service based architecture popular in enterprise Java development. In this Spring or design pattern tutorial we will first see normal implementation of AutditService class, a class in this example which provides auditing in enterprise Java application and than use of dependency Injection. This will  allow us to find out problems and how they are solved by Dependency injection design pattern. . Also there are multiple way to inject dependency in spring e.g. Setter Injection or Constructor Injection, which uses setter method and constructor for injecting dependency, see Setter injection vs Constructor injection  to find out when to use them.
Read more »

Wednesday 14 August 2013

Top Most Difference between Abstract class vs Interface in Java and When to use them

When to use interface and abstract class is one of the most popular object oriented design questions and almost always asked in Java, C# and C++ interviews. In this article, we will mostly talk in context of Java programming language, but it equally applies to other languages as well. Question usually starts with difference between abstract class and interface in Java, which is rather easy to answer, especially if you are familiar with syntax of Java interface and abstract class.Things start getting difficult when interviewer ask about when to use abstract class and interface in Java, which is mostly based upon solid understanding of popular OOPS concept like Polymorphism, Encapsulation, Abstraction, Inheritance and Composition. Many programmer fumbles here, which is natural because most of them haven't gone through real system design process and haven’t seen the impact of choosing one over other. Repercussion of design decisions are best known during maintenance phase, a good design allows seamless evolution while maintaining a fragile design is nightmare. As I have said previously, some time object oriented design interview questions also helps to understand a topic better, but only if you are willing to do some research and not just mugging the answer. Questions like when to use abstract class and interface falls under same category. In order to best understand this topic, you need to work out some scenarios, examples etc. It's best to get this kind of knowledge as part of your work but even if you don't get there, you can supplement them by reading some good books like Head First design pattern and doing some object-oriented software design exercises. In this article, we will learn difference between abstract class and interface in Java programming language and based upon our understanding of those differences, we will try to find out some tips and guidelines to decide when its better to use abstract class over interface or vice-versa.
Read more »

Sunday 11 August 2013

Top Most Difference between Singleton Pattern vs Static Class in Java

Singleton pattern  vs  Static Class (a class, having all static methods) is another interesting questions, which I missed while blogging about Interview questions on Singleton pattern in Java. Since both Singleton pattern and static class provides good accessibility, and they share some similarities e.g. both can be used without creating object and both provide only one instance, at very high level it looks that they both are intended for same task. Because of high level similarities, interviewer normally ask questions like, Why you use Singleton instead of Static Methods, or Can you replace Singleton with static class, and  what are differences between Singleton pattern and static in Java. In order to answer these question, it’s important to remember fundamental difference between Singleton pattern and static class, former gives you an Object, while later just provide static methods. Since an object is always much more capable than a method, it can guide you when to use Singleton pattern vs static methods.
Read more »

Saturday 3 August 2013

Top Most Difference between Factory and Abstract Factory design pattern in Java

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 abstractionover 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
Read more »

Thursday 1 August 2013

Top Most Data Access Object (DAO) design pattern in Java - Tutorial Example

Data Access Object or DAO design pattern is a popular design pattern to implement persistence layer of Java application. DAO pattern is based on abstractionand encapsulationdesign principles and shields rest of application from any change on persistence layer e.g. change of database from Oracle to MySQL, change of persistence technology e.g. from File System to Database. For example if you are authenticating user using relational database and later your company wants to use LDAP to perform authentication. If you are using DAO design pattern to access database, it would be relatively safe as you only need to make change on Data Access Layer. DAO design pattern also keeps coupling low between different parts of application. By using DAO design pattern your View Layer is completely independent to DAO layer and only Service layer has dependency on it which is also abstracted by using DAO interface. You can further use Genericsto template your DAO layer. If you are using Spring than you can leverage JdbcTemplate for performing JDBC calls which saves lot of boiler plate coding. Using DAO pattern to access database is one of the JDBC best practices to follow.
Read more »

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt