JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Singleton Patterns
  • In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.
  • This is useful when exactly one object is needed to coordinate actions across the system.
  • Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.
Purpose
  • Ensure a class only has one instance, and provide a global point of access to it.

Applications
  • There must be exactly one instance of a class, and it must be accessible to clients
    from a wellknown access point.
  • When the sole instance should be extensible by subclassing, and clients should be
    able to use an extended instance without modifying their code.
Non-software examples of Singleton design patterns

The Singleton pattern ensures that a class has only one instance and provides a
global point of access to that instance. It is named after the singleton set, which is
defined to be a set containing one element

Example:-1

InterestFactory.java

package com.factory;

import java.util.HashMap;
import java.util.Map;

import com.model.FDAccountCalculator;
import com.model.InterestCalculator;
import com.model.SavingAccountInterestCalculator;

 
public class InterestFactory {
  private static Map<String , InterestCalculator> maps;
  static{
    maps=new HashMap<String, InterestCalculator>();
    maps.put("s"new SavingAccountInterestCalculator());
    maps.put("f"new FDAccountCalculator());
  }
  public static InterestCalculator create(String type){
    System.out.println(maps.get(type));
    return maps.get(type);
  }
  private InterestFactory(){}
}

FDAccountCalculator.java
package com.model;

public class FDAccountCalculator
 
implements InterestCalculator {
  private double roi=8.0;
  private int duration=3;
  @Override
  public double calculate(double amt) {
    // TODO Auto-generated method stub
    return roi/100.0*amt*duration;
  }

}

InterestCalculator.java
package com.model;

public interface InterestCalculator {
  public double calculate(double amt);
}

SavingAccountInterestCalculator.java
package com.model;

public class SavingAccountInterestCalculator
 
implements InterestCalculator {

  private double roi=3.5;
  @Override
  public double calculate(double amt) {
    // TODO Auto-generated method stub
    return (roi/100.0)*amt/12.0;
  }

}


CalculatorService.java
package com.service;

import com.model.InterestCalculator;

public class CalculatorService {
  private InterestCalculator ic;
  public CalculatorService(InterestCalculator ic){
    this.ic=ic;
  }
  public double service(double amt){
    return ic.calculate(amt);
  }
}

Test.java
package com.test;

import com.factory.InterestFactory;
import com.model.FDAccountCalculator;
import com.model.SavingAccountInterestCalculator;
import com.service.CalculatorService;

public class Test {
  public static void main(String arg[]){
    
    CalculatorService servicer=new
CalculatorService
(InterestFactory.create("s"));
    System.out.println("Interest for Savings
Account for the amount 10000 [Current Month]: "
+servicer
.service
(10000));
    servicer=new CalculatorService(InterestFactory.
create
("s"));
    System.out.println("Interest for Savings Account
for the amount 10000 [Current Month]: "
+servicer.service(10000));
    
    servicer=new CalculatorService(InterestFactory.create("f"));
    System.out.println("Interest for FD Account for the
amount 10000 for 3 years: "
+servicer.service(10000));
    servicer=new CalculatorService(InterestFactory.crea
te
("f"));
    System.out.println("Interest for FD Account for the
 amount 10000 for 3 years: "
+servicer.service(10000));
      
  }
}


Test.java
package com.test;

import com.factory.InterestFactory;
import com.model.FDAccountCalculator;
import com.model.SavingAccountInterestCalculator;
import com.service.CalculatorService;

public class Test {
  public static void main(String arg[]){
 
    
    CalculatorService servicer=new CalculatorService
(
InterestFactory.create("s"));
    System.out.println("Interest for Savings Account for the amount
 10000 [Current Month]: "
+servicer.service(10000));
    servicer=new CalculatorService(InterestFactory.create("s"));
    System.out.println("Interest for Savings Account for the amount
10000 [Current Month]: "
+servicer.service(10000));
    
    servicer=new CalculatorService(InterestFactory.create("f"));
    System.out.println("Interest for FD Account for the amount 10000
 for 3 years: "
+servicer.service(10000));
    servicer=new CalculatorService(InterestFactory.create("f"));
    System.out.println("Interest for FD Account for the amount 10000
 for 3 years: "
+servicer.service(10000));
      
  }
}



Output:-





Database.java
package singletonsExample_1;

public class Database {
  private static Database singleObject;
  private int record;
  private String name;

  public String getName() {
    return name;
  }

  private Database(String n) {
    name = n;
    record = 0;
  }

  public static Database getInstance(String n) {
    if (singleObject == null) {
      System.out.println("nothing");
      singleObject = new Database(n);
      

    }
    System.out.println("something");
    return singleObject;
  }
}

TestSingleton.java
package singletonsExample_1;


public class TestSingleton {
  public static void main(String args[]) {
    Database database;
    database = Database.getInstance("products");
    System.out.println("This is the " +
 database.getName
() " database.");
    database = Database.getInstance("employees");
    System.out.println("This is the "
+ database.getName
() " database.");
  }
}


Output:-




Download Zip code


Example:2

package client2.singleton;

public class Singleton {

  private static final Singleton INSTANCE = new Singleton();

  private Singleton() {

    // Check if we already have an instance
    if (INSTANCE != null) {
      throw new IllegalStateException("Singleton"
          " instance already created.
Message from our program"
);

    }

    System.out.println("Singleton Constructor Running...");
  }

  public static final Singleton getInstance() {
    return INSTANCE;
  }
}


Test.java
   package client2.client;  
    
   import java.lang.reflect.Constructor;  
   import client2.singleton.*;  
   public class Test {  
       public static void main(String[] argsthrows Exception {  
             
           Singleton s = Singleton.getInstance();  
             
           Class clazz = Singleton.class;  
             
           Constructor cons = clazz.getDeclaredConstructor();  
           cons.setAccessible(true);  
             
           Singleton s2 = (Singletoncons.newInstance();    
           Singleton s3 = (Singletoncons.newInstance();
       }  
   }  

Output:-




Test.java
package com.test.singleton.client;  
 
import java.lang.reflect.Constructor;  
import com.test.singleton.securitymgr.*;

public class Test {  
  
    public static void main(String[] argsthrows Exception {  
          
        Singleton s = Singleton.getInstance();  
          
        Class clazz = Singleton.class;  
          
        Constructor cons = clazz.getDeclaredConstructor();  
        cons.setAccessible(true);  
          
        Singleton s2 = (Singletoncons.newInstance();  
    }  
}  

Output:-


Download Zip Code