Archive

Posts Tagged ‘design pattern in java’

Proxy Design Pattern (GOF)

ProxyWhen to use this pattern?
Proxy pattern is used when we need to create a wrapper to cover the main object’s complexity from the client.

  • Provide a surrogate or placeholder for another object to control access to it.
  • Use an extra level of indirection to support distributed, controlled, or intelligent access.
  • Add a wrapper and delegation to protect the real component from undue complexity.

Problem:
You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

What are the usage scenarios?

  1. Virtual Proxy – Imagine a situation where there is multiple database call to extract huge size image. Since this is an expensive operation we can possibly use the proxy pattern which would create multiple proxies and point to the huge size memory consuming object for further processing. The real object gets created only when a client first requests/accesses the object and after that we can just refer to the proxy to reuse the object. This avoids duplication of the object and hence saving memory.
  2. Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources.
  3. Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked.
  4. Smart Proxy – A smart proxy provides additional layer of security by interposing specific actions when the object is accessed. An example can be to check if the real object is locked before it is accessed to ensure that no other object can change it.

Participants:

  1. Subject – This object defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  2. Proxy – It maintains a reference to the RealSubject so that Proxy can access it. It also implements the same interface as the RealSubject so that Proxy can be used in place of RealSubject. Proxy also controls the access to the RealSubject and can create or delete this object.
  3. RealSubject – This refers the main object which the proxy represents.

 

Code Example: –  Virtual Proxy Example:

As mentioned earlier virtual proxy is useful to save expensive memory resources. Let’s take a scenario where the real image contains a huge size data which clients needs to access. To save our resources and memory the implementation will be as below:

– Create an interface which will be accessed by the client. All its methods will be implemented by the ProxyImage class and RealImage class.
– RealImage runs on the different system and contains the image information is accessed from the database.
– The ProxyImage which is running on a different system can represent the RealImage in the new system. Using the proxy we can avoid multiple loading of the image.

Image.java:

public interface Image {
public void showImage();
}

 

RealImage.java:

public class RealImage implements Image {

private String fileName = null;
public RealImage(String strFileName){
this.fileName = strFileName;
}
@Override
public void showImage() {
System.out.println(“Show Image:” +fileName);

}
}

 

 

ProxyImage.java:

public class ProxyImage implements Image {
private RealImage img= null;
private String fileName = null;

public ProxyImage(String strFileName) {
this.fileName = strFileName;
}
/*
* (non-Javadoc)
* @see com.proxy.virtualproxy.Image#showImage()
*/
@Override
public void showImage() {
if(img == null){
img = new RealImage(fileName);
}
img.showImage();
}
}

Client.java:

public class Client {
public static void main(String[] args) {
final Image img1 = new ProxyImage(“Image***1”);
final Image img2 = new ProxyImage(“Image***2”);
img1.showImage();
img2.showImage();
}
}

Benefits:

  •  One of the advantages of Proxy pattern as you have seen in the above example is about security.
  •  This pattern avoids duplication of objects which might be huge size and memory intensive. This in turn increases the performance of the application.
  •  The remote proxy also ensures about security by installing the local code proxy (stub) in the client machine and then accessing the server with help of the remote code.

 

Drawbacks/Consequences:

This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour.

Rules of thumb:
– There are few differences between the related patterns. Like Adapter pattern gives a different interface to its subject, while Proxy patterns provides the same interface from the original object but the decorator provides an enhanced interface. Decorator pattern adds additional behaviour at runtime.

– Proxy used in Java API:  java.rmi.*;

 

 

Factory Method pattern in java

The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The creation of an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

Factory pattern comes into creational design pattern category, the main objective of the creational pattern is to instantiate an object and in Factory Pattern an interface is responsible for creating the object but the sub classes decides which class to instantiate. It is like the interface instantiate the appropriate sub-class depending upon the data passed. Here in this article we will understand how we can create an Factory Pattern in Java

The essence of the Factory method Pattern is to “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses
Use the factory pattern when:

  1.   The creation of the object precludes reuse without significantly duplicating code.
  2.  The creation of the object requires access to information or resources not appropriate to contain within the composing object.
  3.  The lifetime management of created objects needs to be centralised to ensure consistent behavior.

PrintSomething.java

package javainsider.pattern.factory;

public abstract class PrintSomething {

public abstract void printTech();
}

Now we will have the concrete implementations of the printSomething class, JavaTech and J2eeTech, each providing a much simplified implementation for the printTech() method.

JavaTech.java

package javainsider.pattern.factory;

public class JavaTech extends printSomething {
@Override
public void printTech()
{
System.out.println(“this is java technology”);
}

We will having one more class for j2eeTech for j2ee technology.

J2eeTech.java

package javainsider.pattern.factory;

public class J2eeTech extends PrintSomething {
public void printTech()
{
System.out.println(“this is j2ee technology”);
}
}

Now let us come to the core implementation, the Factory class itself. The PrintFactory class has one static method called showPrint() which the clients can invoke to get the printSomething object. Note the return type of the method, it is neither JavaTech nor J2eeTech, but the super type of the both, i.e, printSomething. Whether the return type of method is JavaTech or J2eeTech is decided based on the input operating system.

PrintFactory.java

package javainsider.pattern.factory;

public class PrintFactory {

public static PrintSomething showPrint(String os){

if (os.equals(“Java”))
{

return new JavaTech();

}
else if (os.equals(“J2ee”))
{

return new J2eeTech();

}

return null

}

}

In this we can makes use of the above PrintFactory class. The client is un-aware of the fact there is multiple implementations of the printSomething class. It accesses the printTech() operation through a single unified type printSomething.

FactoryClient.java

package javainsider.pattern.factory;

public class FactoryClient {

public static void main(String[] args) {

PrintSomething psJava =PrintFactory.showPrint(“Java”);

psJava.printTech();

PrintSomething psJ2ee = PrintFactory.showPrint(“j2ee”);

psJ2ee.printTech();

}

%d bloggers like this: