Java Design Patterns – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 03:29:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java Design Patterns – Java2Blog https://java2blog.com 32 32 Strategy design pattern in java https://java2blog.com/strategy-design-pattern-java/?utm_source=rss&utm_medium=rss&utm_campaign=strategy-design-pattern-java https://java2blog.com/strategy-design-pattern-java/#comments Tue, 24 Apr 2018 18:38:47 +0000 https://java2blog.com/?p=5445 In this post, we will see about Strategy design pattern in java.

Strategy design pattern allows us to change algorithm implementation at runtime.Strategy design pattern provides multiple algorithms and client can choose algorithm based on their needs with the help of composition.

Strategy design pattern example

Let’s understand this with the help of simple example.
Let’s say you want to implement multiple sorting algorithms.
You need to sort list based on input sorting type(Merge sort and Quick sort).Please note that there should be provision to add new sorting type in future.

Create an Enum called "SortingType.java" as below.

package org.arpit.java2blog.designpattern;
public enum SortingType {
    MERGE_SORT,QUICK_SORT;
}

Create Service class named SortingManager as below:

package org.arpit.java2blog.designpattern;

import java.util.List;

public class SortingManager {

    List list;

    public SortingManager(List list) {
        super();
        this.list = list;
    }

    public void sortListBasedOnType(SortingType sortingType)
    {
        System.out.println("===================================");
        System.out.println("Sorting List based on Type");
        System.out.println("===================================");

        if("MERGE_SORT".equalsIgnoreCase(sortingType.toString()))
        {
            sortListUsingMergeSort();
        }
        else if("QUICK_SORT".equalsIgnoreCase(sortingType.toString()))
        {
            sortListUsingQuickSort();
        }
    }

    private void sortListUsingMergeSort()
    {
        System.out.println("Sorting List using merge sort");
    }

    private void sortListUsingQuickSort()
    {
        System.out.println("Sorting List using quick sort");
    }
}

Create a main class named "SortingMain.java" which will call SortingManager to sort list.

package org.arpit.java2blog.designpattern;

import java.util.Arrays;
import java.util.List;

public class SortingMain {

    public static void main(String[] args) {
        List list = Arrays.asList(new Integer[]{44,5,3,5,5,64,3});

        SortingManager sm=new SortingManager(list);

        // Sorting using merge sort
        sm.sortListBasedOnType(SortingType.MERGE_SORT);

        System.out.println();

          // Sorting using quick sort
        sm.sortListBasedOnType(SortingType.QUICK_SORT);

    }

}

Output:

===================================
Sorting List based on Type
===================================
Sorting List using merge sort===================================
Sorting List based on Type
===================================
Sorting List using quick sort

As you can see, this is simple code which is working fine.You have tested code and found out that you are able to sort list based on sorting type.

Class diagram without Strategy pattern

Now you need to create one more sorting type i.e. Heap sort.If you notice, you need to make changes as below:
1) You need to make changes in Enum SortingType.

package org.arpit.java2blog.designpattern;
public enum SortingType {
    MERGE_SORT,QUICK_SORT,HEAP_SORT;
}

2) You need to make changes in SortingManager class which you have already tested.

package org.arpit.java2blog.designpattern;

import java.util.List;

public class SortingManager {

    List list;

    public SortingManager(List list) {
        super();
        this.list = list;
    }

    public void sortListBasedOnType(SortingType sortingType)
    {
        System.out.println("===================================");
        System.out.println("Sorting List based on Type");
        System.out.println("===================================");

        if("MERGE_SORT".equalsIgnoreCase(sortingType.toString()))
        {
            sortListUsingMergeSort();
        }
        else if("QUICK_SORT".equalsIgnoreCase(sortingType.toString()))
        {
            sortListUsingQuickSort();
        }
        else if("HEAP_SORT".equalsIgnoreCase(sortingType.toString()))
        {
            sortListUsingHeapSort();
        }
    }

    private void sortListUsingMergeSort()
    {
        System.out.println("Sorting List using merge sort");
    }

    private void sortListUsingQuickSort()
    {
        System.out.println("Sorting List using quick sort");
    }
    private void sortListUsingHeapSort()
    {
        System.out.println("Sorting List using heap sort");
    }
}

Now you can sort list using heap sirt as below.

package org.arpit.java2blog.designpattern;

import java.util.Arrays;
import java.util.List;

public class SortingMain {

    public static void main(String[] args) {
        List list = Arrays.asList(new Integer[]{44,5,3,5,5,64,3});

        SortingManager sm=new SortingManager(list);

        // Sorting using merge sort
        sm.sortListBasedOnType(SortingType.MERGE_SORT);

        System.out.println();

        // Sorting using quick sort
        sm.sortListBasedOnType(SortingType.QUICK_SORT);

                System.out.println();

         // Sorting using heap sort
        sm.sortListBasedOnType(SortingType.HEAP_SORT);

    }

}

Output:

===================================
Sorting List based on Type
===================================
Sorting List using merge sort===================================
Sorting List based on Type
===================================
Sorting List using quick sort===================================
Sorting List based on Type
===================================
Sorting List using heap sort

As you can see, we have to modify at many places which we have already tested and we need to retest all the functionalities again.

Strategy pattern example

Let’s see how Strategy pattern will be able to solve the problem.
Create SortingManager.java as below.

package org.arpit.java2blog.strategy;

import java.util.List;

public class SortingManager {

    SortingStrategy sortingStrategy;
    List<Integer> list;

    public SortingManager(List<Integer> list,SortingStrategy sortingStrategy) {
        super();
        this.list = list;
        this.sortingStrategy=sortingStrategy;
    }

    public void sortList()
    {
        System.out.println("===================================");
        System.out.println("Sorting List based on Type");
        System.out.println("===================================");

        sortingStrategy.sort(list);
    }

    public SortingStrategy getSortingStrategy() {
        return sortingStrategy;
    }

    public void setSortingStrategy(SortingStrategy sortingStrategy) {
        this.sortingStrategy = sortingStrategy;
    }

    public List<Integer> getList() {
        return list;
    }

    public void setList(List<Integer> list) {
        this.list = list;
    }

}

Create an interface called SortingStrategy as below.

package org.arpit.java2blog.strategy;

import java.util.List;

public interface SortingStrategy {
    void sort(List<Integer> list);
}

Create a class named "MergeStrategy.java" for sorting using merge sort.

package org.arpit.java2blog.strategy;

import java.util.List;

public class MergeSortStrategy implements SortingStrategy {

    @Override
    public void sort(List list)
    {
        System.out.println("Sorting List using merge sort");
    }

}

Create a class named "QuickSortStrategy.java" for sorting using quick sort.

package org.arpit.java2blog.strategy;

import java.util.List;

public class QuickSortStrategy implements SortingStrategy {

    @Override
    public void sort(List list) {
        System.out.println("Sorting List using quick sort");
    }

}

Let’s create a main class SortingMain.java now.

package org.arpit.java2blog.strategy;

import java.util.Arrays;
import java.util.List;

public class SortingMain {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(new Integer[]{44,5,3,5,5,64,3});
        MergeSortStrategy mergeSortStrategy=new MergeSortStrategy();
        SortingManager sm=new SortingManager(list,mergeSortStrategy);
        sm.sortList();

        System.out.println();

        QuickSortStrategy quickSort=new QuickSortStrategy();
        sm.setSortingStrategy(quickSort);
        sm.sortList();
    }
}

Output:

===================================
Sorting List based on Type
===================================
Sorting List using merge sort===================================
Sorting List based on Type
===================================
Sorting List using quick sort

Strategy design pattern

Let’s say you want to sort using heap sort.You need to create below changes:
Create another class named "HeapSortStrategy.java" as below.

package org.arpit.java2blog.strategy;
import java.util.List;

public class HeapSortStrategy implements SortingStrategy {
    @Override
    public void sort(List list) {
        System.out.println("Sorting using heap sort");
    }
}

Change in SortingMain.java to add calling code.

package org.arpit.java2blog.strategy;

import java.util.Arrays;
import java.util.List;

public class SortingMain {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(new Integer[]{44,5,3,5,5,64,3});
        MergeSortStrategy mergeSortStrategy=new MergeSortStrategy();
        SortingManager sm=new SortingManager(list,mergeSortStrategy);
        sm.sortList();

        System.out.println();

        QuickSortStrategy quickSort=new QuickSortStrategy();
        sm.setSortingStrategy(quickSort);
        sm.sortList();

        System.out.println();

        HeapSortStrategy heapSort=new HeapSortStrategy();
        sm.setSortingStrategy(heapSort);
        sm.sortList();
    }
}

Output:

===================================
Sorting List based on Type
===================================
Sorting List using merge sort===================================
Sorting List based on Type
===================================
Sorting List using quick sort===================================
Sorting List based on Type
===================================
Sorting using heap sort

As you can see, we did not make any changes SortingManager which was already tested.We just added new class "HeapSortStrategy" which enabled us to sort using Heap sort.

]]>
https://java2blog.com/strategy-design-pattern-java/feed/ 1
Singleton design pattern in java https://java2blog.com/singleton-design-pattern-java/?utm_source=rss&utm_medium=rss&utm_campaign=singleton-design-pattern-java https://java2blog.com/singleton-design-pattern-java/#comments Mon, 23 Apr 2018 18:45:27 +0000 https://java2blog.com/?p=5462 In this post, we will see about Singleton design pattern in java.

Singleton design pattern is one of the simplest design pattern but singleton property can be broken using multithreading, reflection, serialization etc, so you need to be careful while you create the singleton class.

Singleton design pattern restricts a class to create multiple objects so you can create only one instance of singleton class.Singleton classes are used for logging, database connections, caching and thread pool, .etc.

Singleton class

There are many ways to create singleton but it has few common steps.

    • Make constructor private: You need to make the constructor private so you can not create instance of class from outside of the class.
    • Provide static method to access object of singleton class: Create static method which will return object of singleton class.
    • Create instance of same class as public static which will be returned by static method.

Singleton

There are many ways to create Singleton class, we will see each one in detail.

Eager initialization

Eager initialization is one of the simplest ways to create singleton.Object of the class is created once class is loaded into memory.It is done by creating object of the class when we declare reference variable.

Let’s understand with the help of example:

package org.arpit.java2blog.singleton;

public class EagerInitializationSingleton {

    private static final EagerInitializationSingleton instance = new EagerInitializationSingleton();

    private EagerInitializationSingleton()
    {
        // private constructor
    }

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

Even if client does not need singleton object, still instance is created.If your singleton object is not resource intensive, you can still use it but in general, when you use singleton for connection pooling or database connections, it is resource intensive.

Lazy initialization

Lazy initialization is another way of creating singleton.Instead of creating object at time of variable declaration, we can create it in static method getInstance as below

package org.arpit.java2blog.singleton;

public class LazyInitializationSingleton {

    private static LazyInitializationSingleton instance;

    private LazyInitializationSingleton()
    {
        // private constructor
    }

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

Above code will work fine in case of single-threaded system but in case of multithreading, you might end up creating more than one instance of the class.

Thread safe Singleton

The easiest way to create above class thread-safe is to make getInstance method singleton as below.

package org.arpit.java2blog.singleton;

public class ThreadSafeSingleton {

    private static ThreadSafeSingleton instance;

    private ThreadSafeSingleton()
    {
        // private constructor
    }

    public static synchronized ThreadSafeSingleton getInstance()
    {
        if(instance==null)
        {
            instance= new ThreadSafeSingleton();
        }
        return instance;
    }
}

Above approach will work fine and provide thread safety but there is performance cost associated with it as we have made whole method synchronized. Instead of making getInstance method, we can implement double check locking pattern.

Double check locking

Double check locking use synchronized block with extra null check to make sure only one instance is created for singleton class as below.

package org.arpit.java2blog.singleton;

public class ThreadSafeSingletonDoubleCheck {

    private static volatile ThreadSafeSingletonDoubleCheck instance;

    private ThreadSafeSingletonDoubleCheck()
    {
        // private constructor
    }

    public static ThreadSafeSingletonDoubleCheck getInstance()
    {
        if(instance==null)
        {
            synchronized (ThreadSafeSingletonDoubleCheck.class) {
                if(instance==null)
                {   
                    instance= new ThreadSafeSingletonDoubleCheck();
                }
            }

        }
        return instance;
    }
}

Why do you need double check locking? What can be problem with below code.

public static synchronized ThreadSafeSingletonDoubleCheck getInstance()
    {
        if(instance==null)
        {
            synchronized (ThreadSafeSingletonDoubleCheck.class) {

                instance= new ThreadSafeSingletonDoubleCheck();
            }

        }
        return instance;
    }

Let’s say Thread T1 and T2 both found instance as null.Both T1 and T2 are waiting for class level lock.T1 takes the lock and creates the instance of ThreadSafeSingletonDoubleCheck and releases the lock. T2 takes the lock now and it too creates object of singleton which violates our requirement that’s why we require double check lock here.

Bill Pugh Singleton Implementation

Bill pugh singleton implementation is one of the best way to create singleton class. It makes use of static inner class to create singleon class.

package org.arpit.java2blog.singleton;

public class BillPughSingleton {

    private BillPughSingleton()
    {
        // private constructor
    }

     private static class SingletonHelper{
            private static final BillPughSingleton INSTANCE = new BillPughSingleton();
        }

        public static BillPughSingleton getInstance(){
            return SingletonHelper.INSTANCE;
        }
}

When the singleton class is loaded, inner class is not loaded and hence it doesn’t create object of Singleton class when loading the class. Inner class is created only when getInstance() method is called. So it looks like a eager initialization at first, but it is actually lazy initialization.

Create singleton using Enum

As Java Enum are global constants and loaded only once. Joshua Bloch suggested that Enum is best candidate for singleton design pattern. Please note that Java Enum does not allow lazy initialazation, so even if you do not use singleton, it will still be loaded.
Enum exmaple:

package org.arpit.java2blog.singleton;

public enum SingletonEnum {
    INSTANCE;

    // Write other methods
}

As Enum does not provide any explicit constructor, you can not create multiple instance of sinlgeton class even with reflection.

Testing singleton with Reflection

You can easily destroy singleton with the help of reflection for all above implementations excpet Enum.Reflection is powerful mechanism to instantiate the objects.
Let’s understand with the help of example:

package org.arpit.java2blog.singleton;
import java.lang.reflect.Constructor;

public class ReflectionSingletonTest {

    public static void main(String[] args) {
        BillPughSingleton instance1 = BillPughSingleton.getInstance();
        BillPughSingleton instance2 = null;
        try {
            Constructor[] constructors = BillPughSingleton.class.getDeclaredConstructors();
            for (Constructor constructor : constructors) {
                //Below code will destroy the singleton pattern
                constructor.setAccessible(true);
                instance2 = (BillPughSingleton) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Hashcode of instance1: "+instance1.hashCode());
        System.out.println("Hashcode of instance2: "+instance2.hashCode());
    }

}

When you run above program, you will get below output:

Hashcode of instance1: 865113938
Hashcode of instance2: 1442407170

As you can see, Hashcode of instance1 and instance2 are different, so we are able to create two instance of singleton class.

You can restrict the scenario by throwing Runtime Exception when reflection tries to create the instance of object second time as below.

package org.arpit.java2blog.singleton;

public class BillPughSingleton {

    private BillPughSingleton()
    {
        // private constructor
        if(SingletonHelper.INSTANCE!=null)
        {
            throw new RuntimeException("You can not create object of singleton class twice");
        }
    }

     private static class SingletonHelper{
            private static final BillPughSingleton INSTANCE = new BillPughSingleton();
        }

        public static BillPughSingleton getInstance(){
            return SingletonHelper.INSTANCE;
        }

}

When you run ReflectionSingletonTest now, you will get below output.

java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.arpit.java2blog.singleton.ReflectionSingletonTest.main(ReflectionSingletonTest.java:14)
Caused by: java.lang.RuntimeException: You can not create object of singleton class twice
at org.arpit.java2blog.singleton.BillPughSingleton.(BillPughSingleton.java:10)
… 5 more
Hashcode of instance1: 1028566121
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.singleton.ReflectionSingletonTest.main(ReflectionSingletonTest.java:21)

As you can see, above program throws Runtime Exception, when reflection tries to create object of singleton class twice.

Testing singleton with Serialization

When you serialize and deserialize the object of the singleton class, you should get the same object.
Let’s see if we are going to get the same object or not with the help of simple example.
Let’s first make BillPughSingleton class Serializable.

package org.arpit.java2blog.singleton;

import java.io.Serializable;

public class BillPughSingleton implements Serializable{

    private static final long serialVersionUID = 2088778914384963252L;

    private BillPughSingleton()
    {
        // private constructor
        if(SingletonHelper.INSTANCE!=null)
        {
            throw new RuntimeException("You can not create object of singleton class twice");
        }
    }

    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }

}

Let’s create SingletonSerializedTest to test serialization scenario.

package org.arpit.java2blog.singleton;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class SingletonSerializedTest {

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        BillPughSingleton instance1 = BillPughSingleton.getInstance();
        // Serialize the object
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
                "singleton.ser"));
        out.writeObject(instance1);
        out.close();

       // deserialize the object
        ObjectInput in = new ObjectInputStream(new FileInputStream(
                "singleton.ser"));
        BillPughSingleton instance2 = (BillPughSingleton) in.readObject();
        in.close();

        System.out.println("Hashcode of instance1: "+instance1.hashCode());
        System.out.println("Hashcode of instance2: "+instance2.hashCode());
    }
}

When you run above program, you will get below output.

Hashcode of instance1: 589431969
Hashcode of instance2: 295530567

As you can see, Hashcode of instance1 and instance2 are different, so we are able to create two instances of singleton class with help of serialization.
Implement readResolve method to overcome above scenario as below.

protected Object readResolve() {
    return getInstance();
}

When you run SingletonSerializedTest now, you will get below output.

Hashcode of instance1: 589431969
Hashcode of instance2: 589431969

Testing singleton with Cloning.

In case, if your singleton class implements clonable interface, you need to override clone method and throw CloneNotSupportedException from it.

public Object clone() throws CloneNotSupportedException
{
    return new CloneNotSupportedException("You can not clone object of Singleton class ");
}

Let’s create CloningSingleonTest to create cloning scenario.

package org.arpit.java2blog.singleton;

public class CloningSingleonTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        BillPughSingleton instance1 = BillPughSingleton.getInstance();
        BillPughSingleton instance2=(BillPughSingleton) instance1.clone();

        System.out.println("Hashcode of instance1: "+instance1.hashCode());
        System.out.println("Hashcode of instance2: "+instance2.hashCode());
    }

}

When you run above program, you will get below output.

Exception in thread “main” java.lang.ClassCastException: java.lang.CloneNotSupportedException cannot be cast to org.arpit.java2blog.singleton.BillPughSingleton
at org.arpit.java2blog.singleton.CloningSingleonTest.main(CloningSingleonTest.java:7)

That’s all about Singleton Design pattern.

]]>
https://java2blog.com/singleton-design-pattern-java/feed/ 2
How to use connection pool using service locator design Pattern in java https://java2blog.com/connection-pool-using-service-locator-pattern/?utm_source=rss&utm_medium=rss&utm_campaign=connection-pool-using-service-locator-pattern https://java2blog.com/connection-pool-using-service-locator-pattern/#comments Thu, 14 Jul 2016 12:46:00 +0000 http://www.java2blog.com/?p=176

In this post, you will learn about the Connection Pool. This post is intended by java application development experts for entire development community to let people learn and acknowledge about Connection Pool and how to use its object using Service Locator design pattern.

Introduction

Connection pool is a mechanism which applicable for all technologies in the world. We can use tomcat server to configure the connection pool and we should use Service locator design pattern for better connection pool performance.

What is connection pool?

Connection pool is mechanism which avoids to creating new connection with Database for each client request which is coming from Application. Connecting with DB via programming is too expensive. There are many configurable connection pool mechanism in Java. Using connection pool mechanism we can maintain connection object in-memory. Whenever connection object is required, we can reuse the available connection from the pool of memory, instead of creating new connection unless all connection are occupied by the application. This article demonstrate how to configure connection pool in Apache Tomcat server and how to use those connection pool object using Service Locator design pattern.

What is Service Locator design pattern?

Service locator is a J2EE design pattern which tells how to interact with reusable business component which used in across the Application. For example, once you configured the connection pool in tomcat server, all available connection are available in Tomcat server in memory.

How do you get DB connection from the pool for your application?

There are many of ways to get the DB connection which configured in Tomcat Server. The best way is Service Locator design pattern. If want to create a Java class which should have service locator behavior, your class must follow following.
• Your class constructor must be private
• Your class should have static method which return a connection object and delegates to client.
The responsibility of private constructor is to create necessary service which used by application. In our example service locator creates the DBconnection and make it available in the in-memory.

Responsibility of static method is to give the services to client application which created by private constructor.
Following are the configuration and code implementation of creating Connection pool.
DB connection and connection pool configuration in Tomcat server.

In order to configure DB connection in tomcat server, open conf/context.xml and add above resource tag. Apply mysql connection properties as in above xml code. Configure maximum active connection and idle connection pool. In the above example 10 is maximum connection pool and idle is 4. To get this connection object in you java program, you need to create Service locator java class which used globally in your application. Wherever dB connection is need, the Service locator provide the connection object from java in-memory.
Following is static variable in Service Locator class private static Connection connection; Following is a private constructor which create Datasource using lookup method. In this example our datasource name is “jdbc/connectionTest”

private ConnectionPoolService() {

try{

Context initContext = new InitialContext();
Context envContext =(Context)initContext.lookup("java:/comp/env");
DataSource dataSource =(DataSource)envContext.lookup("jdbc/connectionTest");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
}catch(Exception ex){
ex.printStackTrace();
}
}
jdbc/connectionTest is datasource name configured in conf/context.xml file, the lookup method successfully find the datasource name, it will assign to DataSource object. Using Datasource object,we can get the connection object. The above particular code should execute only once in the application because, the same connection object should use wherever db connection required. The entire code is placed in private constructor which means we can’t call this constructor in outside of the class.
public static Connection getConnection() {
 if(connection == null) {
  new ConnectionPoolService();
 }
 return connection;
}
The above method is a static method which returns the connection object. This method invokes the private constructor and creates the connection object. According to this method code, whenever invoke this method, first check the connection object availability. If connection object is not available, it invokes the private constructor to create new connection object. If connection object is already available, this method doesn’t invoke the private constructor instead it will return the available existing connection from the java in-memory. Through this way we can avoid the initializing new connection object for each DBs connection request.
The below code demonstrates that how to get connection object from ConnectionPoolService.
public Customer getCustomerData(long customerId) throws MyDAOException {
  Connection connection = null;
  Customer customer = null;
  try {
    ResultSet resultSet = null;
   connection = ConnectionPoolService.getConnection();
   Statement statement = connection.createStatement();
   String query = "SELECT * FROM customer where customer_id=" + customerId;
   resultSet = statement.executeQuery(query);
   customer = new Customer();
   while (resultSet.next()) {
    customer.setCustomerId(Long.parseLong(resultSet.getString(1)));
    customer.setCustomerName(resultSet.getString(2));
    customer.setEmailId(resultSet.getString(3));
   }

  }catch(Exception ex){
   ex.printStackTrace();
   throw new MyDAOException("Error while connecting db");
  }
finally
{
resultSet.close();
connection.close();
}
  return customer;
}
The above method invokes the following line which returns the connection object.
connection = ConnectionPoolService.getConnection();
This method either directly returns connection from the java in-memory or creates the new connection based on availability of connection object.

Conclusion

Service locator is a J2EE Design pattern which use the concept of Java singleton design pattern. The use of singleton design pattern is to create a java object only once and used in across the application. In our case private constructor create connection object only once. If connection is already available, it reused by the application. Why it is called as Service locator? If private constructor creates only java instance, we can say it is singleton design pattern but the private constructor creating DB resource which is being serviced across the application so, it is called as Service Locator design pattern

Below diagram explains how service locator works to get connection pool object from the tomcat server.

Using service locator mechanism you can adopt this code for any service you want to pick from particular source.

Hope you have understood the use of Connection Pool object with Service locator design pattern in java application development. For any confusion, ask expert assistance.


Bio:- Aaron Jacobson is expertise in java application development. He has been working as a java developers in Technoligent for many years. He major contribute included the collection of web solutions like java, Python, Asp.Net, Mobile Apps etc…. He has extensive experience in java technology and object oriented programming language. You can follow me on twitter@Techno_Ligent and you can add friend on Facebook @TechnoLigent
]]>
https://java2blog.com/connection-pool-using-service-locator-pattern/feed/ 1
Template method design pattern in java https://java2blog.com/template-method-design-pattern-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=template-method-design-pattern-in-java https://java2blog.com/template-method-design-pattern-in-java/#respond Fri, 01 Mar 2013 21:58:00 +0000 http://www.java2blog.com/?p=397
CodeProjectTemplate method pattern is a behavioral design pattern which provide base method for algorithm,called template method which defers some of its steps to subclasses So algorithm structure is same but some of its steps can be redefined by subclasses according to context.

Template means Preset format like HTML templates which has fixed preset format.Similarly in template method pattern,we have a preset structure method called template method which consists of steps.This steps can be abstract method which will be implemented by its subclasses.

So in short you can say,In template method pattern,there is template method which defines set of steps and implementation of steps can be deferred to subclasses.Thus template method defines algorithm but exact steps can be defined in subclasses.

When to use it:

  • When you have a preset format or steps for algorithm but implementation of steps may vary.
  • When you want to avoid code duplication,implementing common code in base class and variation in subclass.

Structure:

So in above diagram,as you can see we have defined template method with three steps i.e. operation1,operation2 and operation3.Among them,opeation1 and operation2 are abstract steps,so these are implemented by ConcreteClass.We have implemented operation3 here.You can implement an operation in base class in two scenario first is if it is common to all and second is if it is default implementation of that method.
UML diagram will be much clearer now.

Components:

AbstractClass
  • It defines template method defining the structure of algorithm.
  • It also defines abstract operations that will be implemented by subclasses to define steps of algorithm.

ConcreteClass

  • It implements abstract operation of super class to carry out subclass specific steps of the algorithm and also overrides operation if default behavior is not required

Important points about template method pattern:

  • Template method in super class follows “the Hollywood principle”: “Don’t call us, we’ll call you”. This refers to the fact that instead of calling the methods from base class in the subclasses, the methods from subclass are called in the template method from superclass.
  • Template method in super class should not be overriden so make it final
  • Customization hooks:Methods containing a default implementation that may be overidden in other  classes are called hooks methods. Hook methods are intended to be overridden, concrete methods are not.So in this pattern,we can provide hooks methods.The problem is sometimes it becomes very hard to differentiate between hook methods and concrete methods.
  • Template methods are technique for code reuse because with this,you can figure out common behavior and defer specific behavior to subclasses.

Example:

Lets take example.When you have to read from two data source i.e CSV and database then you have to process that data and generate output as CSV files.Here three steps are involved.

  1. Read data from correspoding data source
  2. Process data
  3. Write output to CSV files

Java code:

Below class contains template method called “parseDataAndGenerateOutput” which consists of steps for reading data,processing data and writing to csv file.

1.DataParser.java

package org.arpit.javapostsforlearning;

abstract public class DataParser {
    
    //Template method
    //This method defines a generic structure for parsing data
    public void parseDataAndGenerateOutput()
    {
        readData();
        processData();
        writeData();
    }
    //This methods will be implemented by its subclass
    abstract void readData();
    abstract void processData();
    
    //We have to write output in a CSV file so this step will be same for all subclasses
    public void writeData()
    {
        System.out.println("Output generated,writing to CSV");
    }
}
In below class,CSV specific steps are implement in this class
2.CSVDataParser.java
package org.arpit.javapostsforlearning;

public class CSVDataParser extends DataParser {

    void readData() {
        System.out.println("Reading data from csv file");
    }
    void processData() {
        System.out.println("Looping through loaded csv file");    
    }
}
In below class,database specific steps are implement in this class
 
3.DatabaseDataParser.java
package org.arpit.javapostsforlearning;

public class DatabaseDataParser extends DataParser {

    void readData() {
        System.out.println("Reading data from database");
    }

    void processData() {
        System.out.println("Looping through datasets");        
    }
}
4.TemplateMethodMain.java
package org.arpit.javapostsforlearning;

public class TemplateMethodMain {

    /**
     * @author arpit mandliya
     */
    public static void main(String[] args) {
        
        CSVDataParser csvDataParser=new CSVDataParser();
        csvDataParser.parseDataAndGenerateOutput();
        System.out.println("**********************");
        DatabaseDataParser databaseDataParser=new DatabaseDataParser();
        databaseDataParser.parseDataAndGenerateOutput();

    }

}
output:
Reading data from csv file
Looping through loaded csv file
Output generated,writing to CSV
**********************
Reading data from database
Looping through datasets
Output generated,writing to CSV

Used in java API:

Source code:

Source:Download

]]>
https://java2blog.com/template-method-design-pattern-in-java/feed/ 0
Observer design pattern in java https://java2blog.com/observer-design-pattern-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=observer-design-pattern-in-java https://java2blog.com/observer-design-pattern-in-java/#comments Wed, 27 Feb 2013 19:04:00 +0000 http://www.java2blog.com/?p=398 As the name suggests it is used for observing some objects.Observer watch for any change in state or property of subject.Suppose you are interested in particular object and want to get notified when its state changes then you observe that object and when any state or property change happens to that object,it get notified to you.

As described by GoF:
“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically”.

You can think of observer design pattern in two ways

  • Subject-Observer relationship:Object which is being observed is refereed as Subject and classes which observe subject are called Observer
  • Publisher-Subscriber relationship:A publisher is one who publish data and notifies it to the list of subscribers who have subscribed for the same to that publisher. A simple example is Newspaper. Whenever a new edition is published by the publisher,it will be circulated among subscribers whom have subscribed to publisher.

The observers will not monitor every time whether there is any change in state of subject or not, since they will be notified for every state change of subject, until they stop observing subject. So it follows hollywood principle-“Don’t call us,we will call you”.

Some real life examples:

You might have surfed “Flipkart.com-Online megastore”.So when you search for any product and it is unavailable then there is option called “Notify me when product is available”.If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail “Product is available now you can buy it”.In this case,Product is subject and You are an observer.
Lets say,your permanent address is changed then you need to notify passport authority and pan card authority.So here passport authority and pan card authority are observers and You are a subject.

On facebook also,If you subscribe someone then whenever new updates happen then you will be notified.

When to use it:

  • When one object changes its state,then all other dependents object must automatically change their state to maintain consistency
  • When subject doesn’t know about number of observers it has.
  • When an object should be able to notify other objects without knowing who objects are.

 UML diagram for observer design pattern:

Components:

Subject

  • Knows its observers
  • Has any number of observer
  • Provides an interface to attach and detaching observer object at run time

Observer

  • Provides an update interface to receive signal from subject

ConcreteSubject

  • Stores state of interest to ConcreteObserver objects.
  • Send notification to it’s observer

ConcreteObserver

  • Maintains reference to a ConcreteSubject object
  • Maintains observer state consistent with subjects.
  • Implements update operation

Java in-built API for observer pattern:

The java API provides one class and one inteface for implementing observer pattern.
1. java.util.Observable-class
2. java.util.Observer-interface

java.util.Observable:

For being observed,class must extend this class. The subclass becomes observable and override methods of  java.util.Observable and other objects can “observe” changes in state of this object.
Methods:
addObserver(Observer o) :add Observer to the list of observers for this subject.
deleteObserver(Observer o) :delete Observers from the list of observers .
notifyObservers() : notify all the observers if object has changed.
hasChanged() :return true if object has changed.
setChanged() :This method marks object has changed
clearChanged() :this method will indicate that subject has no changes or all the observers has been notified.

java.util.Observer:

The class that performs the “observing” must implement the java.util.Observer interface. There is a single method:
public void update(Observable obj, Object arg) :This method is called whenever the observed object is changed. An application calls an Observable object’s notifyObservers method for notifying to all the observers of change.

Example:

You might have surfed “Flipkart.com-Online megastore”.So when you search for any product and it is unavailable then there is option called “Notify me when product is available”.If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail “Product is available now you can buy it”.

Java code:

Below interface is our subject interface.It consists of method for adding or removing observers and also in condition of state change,notify all observer.

1.Subject.java:

package org.arpit.javapostsforlearning;

public interface Subject {
     public void registerObserver(Observer observer);
     public void removeObserver(Observer observer);
     public void notifyObservers();
}

Below class is our ConcreteSubject class.It implements subject interface thus provide implementation of all above three methods.

2.Product.java:

package org.arpit.javapostsforlearning;

import java.util.ArrayList;

public class Product implements Subject{

    private ArrayList observers = new ArrayList();
    private String productName;
    private String productType;
    String availability;

    public Product(String productName, String productType,String availability) {
        super();
        this.productName = productName;
        this.productType = productType;
        this.availability=availability;
    }

    public ArrayList getObservers() {
        return observers;
    }
    public void setObservers(ArrayList observers) {
        this.observers = observers;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductType() {
        return productType;
    }
    public void setProductType(String productType) {
        this.productType = productType;
    }

    public String getAvailability() {
        return availability;
    }

    public void setAvailability(String availability) {
        this.availability = availability;
        notifyObservers();
    }

    public void notifyObservers() {
        System.out.println("Notifying to all the subscribers when product became available");
         for (Observer ob : observers) {
             ob.update(this.availability );
      }

    }

    public void registerObserver(Observer observer) {
         observers.add(observer);

    }

    public void removeObserver(Observer observer) {
         observers.remove(observer);

    }

}
 Below interface is our observer interface.It consists of single method called “update”

3.Observer.java:

package org.arpit.javapostsforlearning;
public interface Observer {
      public void update(String availability);
}
Below class is our ConcreteObserver class.It implements observer interface and provide implementation for update and other ConcreteObserver specific methods.

4.Person.java:

package org.arpit.javapostsforlearning;
public class Person implements Observer{

    String personName;

    public Person(String personName) {
        this.personName = personName;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public void update(String availabiliy) {

        System.out.println("Hello "+personName+", Product is now "+availabiliy+" on flipkart");
    }
}

5.ObserverPatternMain.java:

package org.arpit.javapostsforlearning;
public class ObserverPatternMain {

    /**
     * @Author arpit mandliya
     */
    public static void main(String[] args) {
        Person arpitPerson=new Person("Arpit");
        Person johnPerson=new Person("John");
       
        Product samsungMobile=new Product("Samsung", "Mobile", "Not available");
       
        //When you opt for option "Notify me when product is available".Below registerObserver method
        //get executed        
        samsungMobile.registerObserver(arpitPerson);
        samsungMobile.registerObserver(johnPerson);
       
        //Now product is available
        samsungMobile.setAvailability("Available");
       
    }
}

Run it:

Notifying to all the subscribers when product became available
Hello Arpit, Product is now Available on flipkart
Hello John, Product is now Available on flipkart
Now in above program,when availability of samsung mobile changes,it get notified subscribers who has subscribed for it.

Using java inbuilt APIs:

1.Product.java:

package org.arpit.javapostsforlearning;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

public class Product extends Observable{
 
   private ArrayList observers = new ArrayList();
    private String productName;
    private String productType;
    String availability;

    public Product(String productName, String productType,String availability) {
        super();
        this.productName = productName;
        this.productType = productType;
        this.availability=availability;
    }

    public ArrayList getObservers() {
        return observers;
    }
    public void setObservers(ArrayList observers) {
        this.observers = observers;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductType() {
        return productType;
    }
    public void setProductType(String productType) {
        this.productType = productType;
    }

    public String getAvailability() {
        return availability;
    }

    public void setAvailability(String availability) {
        if(!(this.availability.equalsIgnoreCase(availability)))
        {
            this.availability = availability;
            setChanged();
            notifyObservers(this,availability);
        }
    }

    public void notifyObservers(Observable observable,String availability) {
        System.out.println("Notifying to all the subscribers when product became available");
         for (Observer ob : observers) {
             ob.update(observable,this.availability);
      }

    }

    public void registerObserver(Observer observer) {
         observers.add(observer);

    }

    public void removeObserver(Observer observer) {
         observers.remove(observer);

    }
}
2.Person.java
package org.arpit.javapostsforlearning;
import java.util.Observable;
import java.util.Observer;

public class Person implements Observer{

    String personName;

    public Person(String personName) {
        this.personName = personName;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public void update(Observable arg0, Object arg1) {
        System.out.println("Hello "+personName+", Product is now "+arg1+" on flipkart");

    }

}

3.ObserverPatternMain.java:

package org.arpit.javapostsforlearning;
public class ObserverPatternMain {

    /**
     * @Author arpit mandliya
     */
    public static void main(String[] args) {
        Person arpitPerson=new Person("Arpit");
        Person johnPerson=new Person("John");
       
        Product samsungMobile=new Product("Samsung", "Mobile", "Not available");
       
        //When you opt for option "Notify me when product is available".Below registerObserver method
        //get executed    
        samsungMobile.registerObserver(arpitPerson);
        samsungMobile.registerObserver(johnPerson);
       
        //Now product is available
        samsungMobile.setAvailability("Available");
        
    }
}

Run it:

Notifying to all the subscribers when product became available 
Hello Arpit, Product is now Available on flipkart
Hello John, Product is now Available on flipkart

Some important points about observer pattern:

  • Loose coupling between Subject and Observer:Only thing subject know about its observers is that observer implements Observer interface.You can register or delete any observer without affecting subject.
  • Support for broadcast communication:Notification about subject state change does not need to specify its receiver.This notification is broadcasted to all interested object that subscribed to it.
  • The one of the problem with this pattern is that debugging become very hard,if you have large number of subscribers because flow of control is implicit between subject and observers.
  • Spurious updates:If criteria for state change is not well defined then sometimes it lead to spurious updates.

Source code:

]]>
https://java2blog.com/observer-design-pattern-in-java/feed/ 2
Builder design pattern in java https://java2blog.com/builder-design-pattern-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=builder-design-pattern-in-java https://java2blog.com/builder-design-pattern-in-java/#comments Sat, 29 Sep 2012 17:03:00 +0000 http://www.java2blog.com/?p=411

Builder design pattern allows to create complex object step by step and also enforces a process to create an object as a finished product.Construction of object should be such that same construction process can create different representations.Director controls the construction of object and only director knows what type of object to create.

For example, You can consider printing of a book.Printing of a book involves various steps such as printing table of content,preface,introduction,chapters and conclusion.Finally you will get complete book object. With the help of same above process,you can print books with different properties.

As described by Gof:
“Separate the construction of a complex object from its representation so that the same construction process can create different representations”

Generic UML diagram for builder design pattern:

Elements:

  • Builder
    • specifies an abstract interface for creating parts of a product object.
  • ConcreteBuilder
    • constructs and assembles parts of the product by implementing the builder interface.
    • defines and keeps track of the representation it creates.
    • provides an interface for retrieving the product.
  • Director
    • constructs an object using builder interface.
  • Product
    • represents the complex object under construction.ConcreteBuilder builds the product’s internal representation and defines the process by which it is assembled.
    • includes classes that define the constituent parts,including interfaces for the assembling the parts into final result.

When to use it:

  • Object creation algorithms should be independent of system.
  • New creation algorithm can be added without changing core code.
  • The construction process must allow different representations for the object that’ s contructed.
  • Runtime control over creation process is required.

WorkFlow:

  • The client creates the director object and configures it with the desired builder object.
  • Director notifies builder whenever a part of product should be built.
  • Builder handles requests from the director and adds parts to the product.
  • The clients retrieves the product from builder.

Example:

You can consider priniting of a book.Printing of a book involves various steps such as printing table of content,preface,introduction,chapters and conclusion.Finally you will get complete book object. With the help of same above process,you can write books with different properties.  BookWriter will instruct bookBuilder to print book in steps and return final book object.

Comparing to generic UML diagram of builder pattern:
  • BookBuilder(Builder)
  • TechnicalBookBuilder(ConcreteBuilder)
  • FictionalBookBuilder(ConcreteBuilder)
  • BookWriter(Director)
  • Book(Product)

Java codes for above classes:
Following class is our product class.Object of this class will be returned by builder.

Book.java (Product):

package org.arpit.javapostsforlearning.designpatterns;

public class Book {

 String introduction;
 String tableOfContent;
 String preface;
 String chapters;
 String glossary;
  
 public void setIntroduction(String introduction) {
  this.introduction = introduction;
 }
 public void setTableOfContent(String tableOfContent) {
  this.tableOfContent = tableOfContent;
 }
 public void setPreface(String preface) {
  this.preface = preface;
 }
 public void setChapters(String chapters) {
  this.chapters = chapters;
 }
 public void setGlossary(String glossary) {
  this.glossary = glossary;
 }
}

Following interface is our builder interface.Builder interface provides steps or process.Here we have five steps-buidTableOfContent,buildPreface,buildIntroduction,buildChapters,buildGlossary.It also has method to return book(product) object. 
BookBuilder.java (Builder):

package org.arpit.javapostsforlearning.designpatterns;

public interface BookBuilder {

        public void buildTableOfContent();
        public void buildPreface();
        public void buildIntroduction();
        public void buildChapters();
        public void buildGlossary();
        public Book getBook();
}

Following class is our first implementation of builder interface.We are having multiple concrete builder class to support  same construction process creating multiple representations.

TechnicalBookBuilder.java(ConcreteBuilder):

package org.arpit.javapostsforlearning.designpatterns;

public class TechnicalBookBuilder implements BookBuilder{
 private Book book;

 public TechnicalBookBuilder()
 {
  book=new Book();
 }
 public void buildTableOfContent() {
  System.out.println("printing technical table of content");
  book.setTableOfContent("technical table of content");
 }
 
 public void buildPreface() {
  System.out.println("printing preface");
  book.setTableOfContent("preface");
 }
 public void buildIntroduction() {
  System.out.println("printing technical introduction");
  book.setTableOfContent("technical introduction");
 }

 public void buildChapters() {
  System.out.println("printing technical chapters");
  book.setChapters("technical chapters");
 }

 public void buildGlossary() {
  System.out.println("printing technical glossary");
  book.setGlossary("Technical glossary");
 }

 public Book getBook() {
  return book;
 }
}

Following class is our second implementation of builder interface.

FictionalBookBuilder.java(ConcreteBuilder):

package org.arpit.javapostsforlearning.designpatterns;

public class FictionalBookBuilder implements BookBuilder{
 private Book book;

 public FictionalBookBuilder()
 {
  book=new Book();
 }
 public void buildTableOfContent() {
  System.out.println("printing fictional table of content");
  book.setTableOfContent("fictional table of content");
 }
 
 public void buildPreface(){
  System.out.println("printing preface");
  book.setTableOfContent("preface");
 }
 public void buildIntroduction() {
  System.out.println("printing fictional introduction");
  book.setTableOfContent("fictional introduction");
 }

 public void buildChapters() {
  System.out.println("printing fictional chapters");
  book.setChapters("fictional chapters");
 }

 public void buildGlossary() {
  System.out.println("printing fictional glossary");
  book.setGlossary("Fictional glossary");
 }

 public Book getBook() {
  return book;
 }

}

Following class is our director class which will instructs BookBuilder to print parts of book and return final book object
BookWriter.java(Director):

package org.arpit.javapostsforlearning.designpatterns;
public class BookWriter {

 BookBuilder bookBuilder;
 
 public BookWriter(BookBuilder bookBuilder) {
  super();
  this.bookBuilder = bookBuilder;
 }

 public Book getBook()
 {
  return this.bookBuilder.getBook();
 }
 
 public void printBook()
 {
  this.bookBuilder.buildTableOfContent();
  this.bookBuilder.buildPreface();
  this.bookBuilder.buildIntroduction();
  this.bookBuilder.buildChapters();
  this.bookBuilder.buildGlossary();
 }
}

BuilderDesignPatternMain.java:

package org.arpit.javapostsforlearning.designpatterns;
public class BuilderDesignPatternMain {
 
 
 public static void main(String[] args) {
  
  System.out.println(Printing technical book:");
  BookBuilder technialbookBuilder=new TechnicalBookBuilder();
  BookWriter technicalBookWriter=new BookWriter(technialbookBuilder);
  technicalBookWriter.printBook();
  Book technicalbook=technicalBookWriter.getBook();
  System.out.println("Technical Book Printed:"+technicalbook);
  System.out.println("******************************************");
  System.out.println(Printing fictional book:");
  BookBuilder fictionalbookBuilder=new FictionalBookBuilder();
  BookWriter fictionalBookWriter=new BookWriter(fictionalbookBuilder);
  fictionalBookWriter.printBook();
  Book fictionalbook=fictionalBookWriter.getBook();
  System.out.println("Fictionalbook book printed:"+fictionalbook);
 }
}

For printing technical book,we have configured bookWriter object with technicalBookBuilder.BookWriter instructed to technicalbookbuilder to print book and return final book object.Same is true for fictional book.So with help of same construction process,we have printed two kinds of book.i.e. technical and fictional.
Output:

Printing technical book:
printing technical table of content
printing preface
printing technical introduction
printing technical chapters
printing technical glossary
Technical Book printed:org.arpit.javapostsforlearning.designpatterns.Book@1888759
******************************************
Printing fictional book:
printing fictional table of content
printing preface
printing fictional introduction
printing fictional chapters
printing fictional glossary
Fictionalbook book printed:org.arpit.javapostsforlearning.designpatterns.Book@1f1fba0

References:The Gang of Four (GoF) book

]]>
https://java2blog.com/builder-design-pattern-in-java/feed/ 2
Proxy design pattern in java https://java2blog.com/proxy-design-pattern-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=proxy-design-pattern-in-java https://java2blog.com/proxy-design-pattern-in-java/#respond Fri, 28 Sep 2012 20:36:00 +0000 http://www.java2blog.com/?p=412
CodeProjectProxy design pattern allows you to create a wrapper class over real object.Wrapper class which is proxy,controls access to real object so in turn you can add extra functionalities to real object without changing real object’s code.
As described by GoF:

“Provide a surrogate or placeholder for another object to control access over it.”

Real life example may be proxy server used in IT companies for internet access.It blocks access to social networking sites like facebook,twitter and other contents which are not work related.

When to use it:

Proxy is required whenever there is need for more sophisticated or versatile reference to an object than a simple pointer.Here are some situations when proxy pattern is applicable.
  1. A remote proxy provides a local representative for an object in a different address space.Providing interface for remote resources such as web service or REST resources.
  2. A virtual proxy creates expensive object on demand.
  3. A protection proxy controls access to the original object.Protection proxies are useful when objects should have different access rights.
  4. A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.
  5. Adding a thread-safe feature to an existing class without changing the existing class’s code.

UML diagram for proxy design pattern:

Elements:

  • Proxy
    • maintains a reference that lets the proxy access the real subject.Proxy may refer to a subject if the RealSubject and Subject interface are the same.
    • provides an interface identical to Subject’s so that proxy can be substituted for the real subject.
    • controls access to the real subject and may be responsible for creating and deleting it.
  • Subject
    • defines the common interface for RealSubject and proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • RealSubject
    • defines the real object that proxy represents. 

WorkFlow:

Proxy forwards request to RealSubject when appropriate ,depending on the kind of proxy.

Example:

Let’s see an example.I am taking example of protection proxy. In our example, we have a folder in which you can perform various operation such as copy,paste file or subfolder.In OOP terms,we have IFolder interface and Folder class which provides performOperatons() method, and these are the existing class and interface that we cannot change. We want to further specify that only user with authorization can access it and perform operations such as cut or copy files and sub folder.

UML diagram for example:

Comparing with above generic elements,we have

  • FolderProxy(Proxy)
  • Folder(RealSubject)
  • IFolder(Subject)

Java codes for above classes:

IFolder.java (Subject):

package org.arpit.javapostsforlearning.designpatterns;

public interface IFolder {

    public void performOperations();
}

Following class is our realSubject class.Lets say we can not change it but we want to provide authorization on it.
Folder.java (RealSubject):

package org.arpit.javapostsforlearning.designpatterns;

public class Folder implements IFolder{
 
 public void performOperations()
 {
       // access folder and perform various operations like copy or cut files
  System.out.println("Performing operation on folder");
 }

}

Following class provides authorization to Folder class.It checks for userName and password and if matched then only it gives access to folder.
FolderProxy.java(Proxy):

package org.arpit.javapostsforlearning.designpatterns;

public class FolderProxy implements IFolder{

 Folder folder;
 User user;
  
 public FolderProxy(User user) {
  this.user = user;
 }


 public void performOperations() {
  
  if(user.getUserName().equalsIgnoreCase("arpit") && user.getPassword().equalsIgnoreCase("arpit"))
  {
   folder=new Folder();
   folder.performOperations();
  }
  else
  {
   System.out.println("You don't have access to this folder");
  }
      }
}

User.java:

package org.arpit.javapostsforlearning.designpatterns;

public class User {

 String userName;
 String password;
  
 public User(String userName, String password) {
  this.userName = userName;
  this.password = password;
 }
 
 public String getUserName() {
  return userName;
 }
 public String getPassword() {
  return password;
 }
 
}

ProxyDesignPatternMain.java:

package org.arpit.javapostsforlearning.designpatterns;

public class ProxyDesignPatternMain {

 public static void main(String[] args) {
  
  //When you click on folder,Lets say a GUI form will ask for userName and password.
  //and this GUI will create this user object
  
  // If we give correct userName and password
  User user=new User("arpit","arpit");
  FolderProxy folderProxy=new FolderProxy(user);
  System.out.println("When userName and password are correct:");
  folderProxy.performOperations();
  System.out.println("**************************************");
  // if we give wrong userName and Password
  User userWrong=new User("abc","abc");
  FolderProxy folderProxyWrong=new FolderProxy(userWrong);
  System.out.println("When userName and password are incorrect:");
  folderProxyWrong.performOperations();
 }

}

Output:

When userName and password are correct:
Performing operation on folder
**************************************
When userName and password are incorrect:
You don't have access to this folder

So without changing Folder class,we have provide authentication to folder with the help of FolderProxy class.

Source code:

Source:Download

]]>
https://java2blog.com/proxy-design-pattern-in-java/feed/ 0
Composite design pattern in java https://java2blog.com/composite-design-pattern-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=composite-design-pattern-in-java https://java2blog.com/composite-design-pattern-in-java/#respond Wed, 19 Sep 2012 16:36:00 +0000 http://www.java2blog.com/?p=413

CodeProjectComposite design patten allows you to have a tree structure and ask each node in the tree structure to perform a task.You can take real life example of a organization.It have general managers and under general managers, there can be managers and  under managers there can be developers.Now you can set a tree structure and ask each node to perform common operation like getSalary().

As described by Gof:
“Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly”.

Composite design pattern treats each node in two ways-Composite or leaf.Composite means it can have other objects below it.leaf means it has no objects below it.

Tree structure:

When to use it:

  • you want to represent part-whole hierachies of objects.
  • you want client to be able to ignore difference between compositions of objects and individual objects.Clients will treat all objects in the composite structure uniformly.

UML Diagram for Composite design pattern:

Elements:

  • Component
    • declares interface for objects in composition.
    • implements deafault behaviour for the interface common to all classes as appropriate.
    • declares an interface for accessing and managing its child components.
  • Leaf
    • represents leaf objects in the composition.A leaf has no children.
    • defines behaviour for primitive objects in the composition.
  • Composite
    • defines behaviour for components having children.
    • stores child components.
    • implements child related operations in the component interface.
  • Client
    • manipulates objects in the composition through the component interface.

WorkFlow:

Client use the component class interface to interact with objects in the composition structure.if recipient is a leaf then request is handled directly.If recipient is a composite,then it usually forwards request to its child components,possibly performing additional operations before and after forwarding.

Recursion:

What makes the Composite pattern one of the most beautiful is the power of recursion. I can explain this with the same organization example. You want to find the total salary paid to all employees of the organization. It is nothing but the salary of CEO + the salary paid to all the departments. What is the salary of a department? It is the salary of the department head + the salary of all projects. What is the total salary of a project? It is the salary of the project manager + the salary of all the project members. In short, the salary of anything is the salary of self + the salary of all its sub groups.

Example:

In a small organization,there are 5 employees.At top position,there is 1 general manager.Under general manager,there are two employees,one is manager and other is developer and further manager has two developers working under him.We want to print name and salary of all employees from top to bottom.

Tree structure for example:

UML diagram for above example:

Comparing from above generic elements.Our example consist of following elements.

  • Manager(Composite)
  • Developer(Leaf)
  • Employee(Component)

Java code for all above classes:

First we will create component inrteface.It represents object in composition .It has all common operation that will be applicable to both manager and developer.
Employee.java(Component) :
package org.arpit.javapostsforlearning.designpatterns;

public interface Employee {

     public void add(Employee employee);
     public void remove(Employee employee);
     public Employee getChild(int i);
     public String getName();
     public double getSalary();
     public void print();
}
Now we will create manager(composite class).Key point here is that all common method delegates its operations to child objects.It has method to access and modify its children.

Manager.java(Composite):
package org.arpit.javapostsforlearning.designpatterns;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Manager implements Employee{

 private String name;
 private double salary;

 public Manager(String name,double salary){
  this.name = name;
  this.salary = salary;
 }
 
 List employees = new ArrayList();
 public void add(Employee employee) {
    employees.add(employee);
 }

 public Employee getChild(int i) {
  return employees.get(i);
 }

 public String getName() {
  return name;
 }

 public double getSalary() {
  return salary;
 }

 public void print() {
  System.out.println("-------------");
  System.out.println("Name ="+getName());
  System.out.println("Salary ="+getSalary());
  System.out.println("-------------");
  
  Iterator employeeIterator = employees.iterator();
    while(employeeIterator.hasNext()){
     Employee employee = employeeIterator.next();
     employee.print();
    }
 }

 public void remove(Employee employee) {
  employees.remove(employee);
 }

}
We will create developer class.This class is leaf node so all operations related to accessing children will be empty as it has no children.
Developer.java(Leaf):

package org.arpit.javapostsforlearning.designpatterns;
/**
 * In this class,there are many methods which are not applicable to developer because
 * it is a leaf node.
 */

public class Developer implements Employee{

    private String name;
    private double salary;

    public Developer(String name,double salary){
        this.name = name;
        this.salary = salary;
    }
    public void add(Employee employee) {
        //this is leaf node so this method is not applicable to this class.
    }

    public Employee getChild(int i) {
        //this is leaf node so this method is not applicable to this class.
        return null;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void print() {
        System.out.println("-------------");
        System.out.println("Name ="+getName());
        System.out.println("Salary ="+getSalary());
        System.out.println("-------------");
    }

    public void remove(Employee employee) {
        //this is leaf node so this method is not applicable to this class.
    }

}
CompositeDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;

public class CompositeDesignPatternMain {

 public static void main(String[] args) {
  Employee emp1=new Developer("John", 10000);
  Employee emp2=new Developer("David", 15000);
  Employee manager1=new Manager("Daniel",25000);
  manager1.add(emp1);
  manager1.add(emp2);
  Employee emp3=new Developer("Michael", 20000);
  Manager generalManager=new Manager("Mark", 50000);
  generalManager.add(emp3);
  generalManager.add(manager1);
  generalManager.print();
 }
}
Output:
-------------
Name =Mark
Salary =50000.0
-------------
-------------
Name =Michael
Salary =20000.0
-------------
-------------
Name =Daniel
Salary =25000.0
-------------
-------------
Name =John
Salary =10000.0
-------------
-------------
Name =David
Salary =15000.0
-------------

Disadvantages:

  • Once tree structure is defined,comosite design makes tree overly general.
  • Leaf class have to create some methods which has to empty.

Usage in JDK:

  • java.util.Map#putAll(Map)
  • java.util.List#addAll(Collection)
  • java.util.Set#addAll(Collection)
  • java.nio.ByteBuffer#put(ByteBuffer) (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
  • java.awt.Container#add(Component)
]]>
https://java2blog.com/composite-design-pattern-in-java/feed/ 0
Adapter design pattern in java https://java2blog.com/adapter-design-pattern-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=adapter-design-pattern-in-java https://java2blog.com/adapter-design-pattern-in-java/#respond Wed, 19 Sep 2012 15:36:00 +0000 http://www.java2blog.com/?p=414

CodeProjectReal life example:

A very simple example is using phone charger. Suppose your mobile phone needs 9 Volts of supply to get charged but main supply is 220 V which is not what you require but it can be a source and you can have something that can get 9 V out of this 220 V and supply to your phone for charging.
Now phone charger is acting as an adapter for you.  So Basically it is making a relationship between two unrelated interfaces. This  is how Adpater pattern works.

Intent:

As described by Gof:
“Convert the interface of class into another interface clients expect.Adapter lets class work together that couldn’t otherwise because of incompatible interfaces”.

Also known as:

Wrapper

UML diagram of generic adapter design pattern:

Elements:

  • Target
    • defines domains-specific interface client uses.
  • Client
    • collaborates with objects conforming to target interface.
  • Adaptee
    • defines existing interface that needs adapting
  • Adapter
    • adapts the interface of adaptee to target interface.

WorkFlow:

Clients call operations on the adapter instance.In turn adapter calls adaptee operations that carry out the request.

When to use it:

  • You want to use existing class and its interface does not match the one you need.
  • You want to create a resuable class that cooperates with unrelated or unforeseen classes that is, class that don’t necessarily have compatible interfaces.

Example:

UML Diagram for example:

Comparing to above generic description of adapter pattern.

My example includes following elements:

  • PrintableList(Target)
  • PrintString(Adaptee)
  • PrintableListAdapter(Adapter)

Java code for all above classes:

Consider that we have a third party library that provides print string functionality through PrintString class.
This is our Adaptee. I know this is silly assumpsion but lets go with it for now.

PrintString.java(Adaptee) :

package org.arpit.javapostsforlearning.designpatterns;

public class PrintString {

 public void print(String s)
 {
  System.out.println(s);
 }
}

Client deals with ArrayList but not with string.We have provided a PrintableList interface that expects the client input.This is our target.

PrintableList.java(Target):

package org.arpit.javapostsforlearning.designpatterns;

import java.util.ArrayList;

public interface PrintableList {
 void printList(ArrayList list);
}
Lets assume we can not change it now.
Finally we have PrintableListAdapter class which will implement PrintableList interface and will deal with our adaptee class.
PrintableListAdapter.java(Adapter):
package org.arpit.javapostsforlearning.designpatterns;

import java.util.ArrayList;

public class PrintableListAdapter implements PrintableList{

 public void printList(ArrayList list) {
 
  //Converting ArrayList to String so that we can pass String to
  // adaptee class
  String listString = "";

  for (String s : list)
  {
      listString += s + "t";
  }
  
  // instantiating adaptee class
  PrintString printString=new PrintString();
  ps.print(listString);
 }
}
AdapterDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;

import java.util.ArrayList;
public class AdapterDesignPatternMain {
 
 public static void main(String[] args)
 {
  ArrayList list=new  ArrayList();
  list.add("one");
  list.add("two");
  list.add("three");
  PrintableList pl=new PrintableListAdapter();
  pl.printList(list);
  
 }
}

Output:

one two three
]]>
https://java2blog.com/adapter-design-pattern-in-java/feed/ 0