Thursday 21 March 2019

                                                        singleton design pattern in java?



Java Singleton
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.
Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.
Java Singleton Pattern
To implement a Singleton pattern, we have different approaches but all of them have the following common concepts.
Private constructor to restrict instantiation of the class from other classes.
Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
============================================================================================================================================================================================
Eager initialization
In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.
If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc. We should avoid the instantiation until unless client calls the getInstance method. Also, this method doesn’t provide any options for exception handling.
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public String printName(String s1)
{
return s1;
}
public static EagerInitializedSingleton getInstance(){
return instance;
}
public static void main(String args[])
{
EagerInitializedSingleton eis=EagerInitializedSingleton.getInstance();
String s1=eis.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:-------------
E:\>javac EagerInitializedSingleton.java
E:\>java EagerInitializedSingleton
Govind Ballabh Khan
=========================================================================================================================================================================================
Static block initialization
Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.
Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create a Singleton class that supports lazy initialization.
public class StaticBlockSingleton {
private static StaticBlockSingleton instance;
private StaticBlockSingleton(){}
public String printName(String s1)
{
return s1;
}
//static block initialization for exception handling
static{
try{
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException("Exception occured in creating singleton instance");
}
}
public static StaticBlockSingleton getInstance(){
return instance;
}
public static void main(String args[])
{
StaticBlockSingleton sbs=StaticBlockSingleton .getInstance();
String s1=sbs.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:-------------
E:\>javac StaticBlockSingleton.java
E:\>java StaticBlockSingleton
Govind Ballabh Khan
=======================================================================================================================================================================================
Lazy Initialization
Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.
The above implementation works fine in case of the single-threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if condition at the same time. It will destroy the singleton pattern and both threads will get the different instances of the singleton class. In next section, we will see different ways to create a thread-safe singleton class.
public class LazyInitializedSingleton {
private static LazyInitializedSingleton instance;
private LazyInitializedSingleton(){}
public String printName(String s1)
{
return s1;
}
public static LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new LazyInitializedSingleton();
}
return instance;
}
public static void main(String args[])
{
LazyInitializedSingleton lis=LazyInitializedSingleton .getInstance();
String s1=lis.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:--------------------------------------
E:\>javac LazyInitializedSingleton.java
E:\>java LazyInitializedSingleton
Govind Ballabh Khan
============================================================================================================================================================================================
Thread Safe Singleton
The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.
Above implementation works fine and provides thread-safety but it reduces the performance because of the cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization).
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton(){}
public String printName(String s1)
{
return s1;
}

public static synchronized ThreadSafeSingleton getInstance(){
if(instance == null){
instance = new ThreadSafeSingleton();
}
return instance;
}
public static void main(String args[])
{
ThreadSafeSingleton tss=ThreadSafeSingleton .getInstance();
String s1=tss.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:----------------------------------------------------------------
C:\Users\govin>e:
E:\>javac ThreadSafeSingleton.java
E:\>java ThreadSafeSingleton
Govind Ballabh Khan

Sunday 17 March 2019



                                          Overriding Concept In Java



Case :1:-Overriding
public class Parent {
              
               public void property()
               {
                              System.out.println("Cash+Land+Gold");
                             
               }
              
               public void marry()
               {
                              System.out.println("Arrange Marriage");
               }

}

class Child extends Parent
{

               public void marry()
               {
                              System.out.println("Love Marriage");
               }
              
}

class Test
               {
                              public static void main(String[] args) {
                                             Parent p=new Parent();
                                             p.marry();//Arrange Marriage
                                             Child c=new Child();
                                             c.marry();//Love Marriage
                                             Parent p1=new Child();
                                             p1.marry();//Love Marriage
                              }
              

}





Case :2:-Overriding(return type May be different –Covariant Type)

public class Parent {
     
     
      public Object m1()
      {
            System.out.println("Object ");
            return null;

     }
     }

class Child extends Parent
{

      public String m1()
      {
            System.out.println("String");
            return null;
      }
     
}

class Test
      {
            public static void main(String[] args) {
                  Parent p=new Parent();
                  p.m1();//Object
                  Child c=new Child();
                  c.m1();//String
                  Parent p1=new Child();
                  p1.m1();//String
            }
     

}












Case :3:-Overriding(private method cannot Override)


public class Parent {
              
              
               private void m1()
               {
                              System.out.println("Parent Class Method");
                             

     }
     }

class Child extends Parent
{

               private void m1()///Compile time Error(Overriding Concept not available for private method)
               {
                              System.out.println("Child Class Method");
                             
               }
              
}



class Test
               {
               public static void main(String[] args)
 {
               Parent p=new Parent();
               p.m1();//Compile time Error(Overriding Concept not available for private method)
               Child c=new Child();
               c.m1();//Compile time Error
               Parent p1=new Child();
               p1.m1();//Compile time Error
}
}








Case :4:-Overriding(final method cannot Override)

public class Parent {
              
              
               public final void m1()
               {
                              System.out.println("Parent Class Final Method");
                             

     }
     }

class Child extends Parent
{

               public void m1()
               {
                              System.out.println("Child Class Method");
                             
               }
              
}

Case :5:-Overriding(Must Be Override Bcz method is abstract)

abstract public class Parent
{
public abstract void m1();
}

class Child extends Parent
{

               public void m1()
               {
                              System.out.println("Must be Override bcz Method is abstract");
                             
               }
              
}






class Test
               {
                              public static void main(String[] args) {
                                             //Parent p=new Parent();//Cannot Create Object bcz   it isAbstract Class
                                             Child c=new Child();
                                             c.m1();//Must be Override bcz Method is abstract
                                             Parent p1=new Child();
                                             p1.m1();//Must be Override bcz Method is abstract
                              }
}

Case :6:-Overriding(We can override non abstract method as abstract)


abstract public class Parent
{

      public void m1()
      {
System.out.println(" We can stop the availability of parent  method implementation to the next level child classes ");
           
      }
     
}

abstract class Child extends Parent
{
public abstract void m1();
}




Case :7:-Overriding(We can’t reduce the scope of access modifier but we can increase  the scope.)

 public class Parent
{

               public void m1()
               {
                              System.out.println(" Method Modifier is public");
                             
               }
              
}

 class Child extends Parent
{
 void m1()//compile time error
 {
                System.out.println("Method Modifier is Default");
 }
}
Case :8:-Overriding(if child class method throws any Checked Exception compulsory parent class method should throw the same checked Exception or its parents otherwise we will get compile time error)


import java.io.*;
 public class Parent
{

               public void m1() throws IOException
               {
                              System.out.println("  ");
                             
               }
              
}

 class Child extends Parent
{
 public void m1() throws EOFException,InterruptedException//compile time error
 {
                System.out.println(" ");
 }
}

Case :9:-Overriding:- we cannot override static method as non static otherwise we will get compile time error.

 public class Parent
{

               public static void m1()
               {
                              System.out.println("  ");
                             
               }
              
}

 class Child extends Parent
{
 public void m1() //compile time error
 {
                System.out.println(" ");
 }
}

Case :10:-Overriding:- we cannot override non static method as static otherwise we will get compile time error.


public class Parent
{

               public  void m1()
               {
                              System.out.println("  ");
                             
               }
              
}

 class Child extends Parent
{
                public static void m1()
                              {
                                             System.out.println("  ");
                                            
                              }
                                }

Case :11:-Overriding:- (Method Hiding)


 public class Parent
{

               public static void m1()
               {
                              System.out.println(" Method Hiding Parent  ");
                             
               }
              
}

 class Child extends Parent
{
                public static void m1()
                              {
                                             System.out.println(" Method Hiding Child ");
                                            
                              }
                             
}


              
               class Test
               {
                              public static void main(String[] args) {
                                             Parent p=new Parent();
                                             p.m1();// Method Hiding Parent
                                             Child c=new Child();
                                             c.m1();// Method Hiding Child
                                             Parent p1=new Child();
                                             p1.m1();// Method Hiding Parent(Method resolution  take care by  compiler on                   //the basis on reference type
                              }
}






Case :12:-Overriding:- (Overriding With Respect to var args method)

public class Parent
{

               public  void m1(int ...x)
               {
                              System.out.println(" Parent  ");
                             
               }
              
}

 class Child extends Parent
{
                public  void m1(int x)
                              {
                                             System.out.println("Child ");
                                            
                              }
                             
}



               class Test
               {
                              public static void main(String[] args) {
                                             Parent p=new Parent();
                                             p.m1(10);// Parent
                                             Child c=new Child();
                                             c.m1(10);// Child
                                             Parent p1=new Child();
                                             p1.m1(10);// Parent   it is overloading but not overriding
                              }
                             
              

}







Case :13:-Overriding:- (Overriding With Respect to variable)


 public class Parent
{

               int x=888;
              
}

 class Child extends Parent
{
                int x=999;
                             
}


              
               class Test
               {
                              public static void main(String[] args) {
                                             Parent p=new Parent();
                                             System.out.println(p.x);// 888
                                             Child c=new Child();
                                             System.out.println(c.x);//999
                                             Parent p1=new Child();
                                          System.out.println(p1.x);//888
                              }
                              }

//variable resolution always takes care by compiler based  on Reference type.(Overriding concept aapplicable only for methods but not for variables)