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

September 30, 2011

Service Locator & Business Delegate Design Patterns for an EJB Client

HelloClient.java - This is the EJB Client class

package info.icontraining.ejb.client;

public class HelloClient {
 
   public static void main(String[] args) {  
      System.out.println(MyBusinessDelegate.sayHello("Dinesh"));
   }
}

MyBusinessDelegate.java

package info.icontraining.ejb.client;

import java.util.Hashtable;
import javax.naming.*;

public class MyBusinessDelegate {

   public static String sayHello(String name) {

      Object obj = MyServiceLocator.getStub("MyEarApp/" 
                  + HelloUserBean.class.getSimpleName() + "/remote");
  
      HelloUser helloUser = (HelloUser) obj;
      return helloUser.sayHello(name);
   }
}

MyServiceLocator.java


package info.icontraining.ejb.client;

import java.util.Hashtable;
import javax.naming.*;

public class MyServiceLocator {

   public static Object getStub(String jndiName) {
  
      Hashtable env = new Hashtable(); 
      env.put("java.naming.factory.initial",
            "org.jnp.interfaces.NamingContextFactory");
      env.put("java.naming.factory.url.pkgs",
            "org.jboss.naming:org.jnp.interfaces"); 
      env.put("java.naming.provider.url","localhost:1099"); 

      Context context;
      Object obj = null;
     
      try {
         context = new InitialContext(env);
         obj = context.lookup(jndiName);
      } catch (NamingException e) {
         e.printStackTrace();
      }

      return obj;
   }
}

Adapter Design Pattern code example in Java

Adaptee Concrete

public class Plug {
   private String specification = "5 AMP";
   public String getInput() {
      return specification;
   }
}

Target interface

public interface Socket {
   public String getOutput();
}

Adapter Concrete

public class PlugAdapter implements Socket {

   Plug plug;

   public String getOutput() {
      plug = new Plug();
      String output = plug.getInput();
      return output;
   }
}

Client

public class Client {
   Socket socket;

   public void m1() {
      socket = new PlugAdapter();
      socket.getOutput();
   }
}

Singleton Design Pattern code example in Java

Singleton Class

public class SingletonClass {

   private static SingletonClass uniqueInstance;
   // other variables here

   private SingletonClass() { }

   public static synchronized SingletonClass getInstance() {

      if (uniqueInstance == null)
         uniqueInstance = new SingletonClass();
      return uniqueInstance;
   }

   // other methods here
}

Decorator Design Pattern code example in Java

Abstract Type


public interface IEmail {
   public String getContents();
}

Concrete Type

public class Email implements IEmail {
   private String content;
   public Email(String content) {
      this.content = content;
   }

   @Override
   public String getContents() {
      //general email stuff
      return content;
   }
}

Abstract Type Decorator

public abstract class EmailDecorator implements IEmail {
  
   //wrapped component
   IEmail originalEmail;

   public IEmail getOriginalEmail() {
      return this.originalEmail;
   }

   public void setOriginalEmail(IEmail email) {
      this.originalEmail = email;
   }
}

Concrete Type Decorator

public class SecureEmailDecorator extends EmailDecorator {

   private String content;
   public SecureEmailDecorator(IEmail basicEmail) {
      setOriginalEmail(basicEmail);
   }

   @Override
   public String getContents() {
      //  secure original
      content = encrypt(getOriginalEmail().getContents());
      return content;
   }

   private String encrypt(String message) {
      //encrypt the string
      return  encryptedMessage;
   }
}

Client

public class EmailSender {

   public void sendEmail(IEmail email) {
      // get hold of email contents
      email.getContents();

      // send email code here
   }

   public static void main(String[] args) {
      EmailSender emailSender = new EmailSender();

      IEmail email = new Email();

      // Sending normal email
      emailSender.sendEmail(email);

      // Sending Secure email
      emailSender.sendEmail(new SecureEmailDecorator(email));
   }
}

Observer Design Pattern code example in Java

The Subject Abstract Type

import Observer;

public interface Subject {
   public void addObserver(Observer o);
   public void removeObserver(Observer o);
   public String getState();
   public void setState(String state);
}

The Observer Abstract Type

import Subject;

public interface Observer {
   public void update(Subject s) { ... }
}

Concrete Implementation of Observer Abstract Type (Subscriber)

import Subject;

public class ObserverImpl implements Observer {
   private String state = "";

   public void update(Subject o) {
      state = o.getState();
      System.out.println("Update received from Subject, state changed to : " + state);
   }
}

Concrete Implementation of Subject Abstract Type (Publisher)

import Observer;

public class SubjectImpl implements Subject {
   private List observers = new ArrayList();

   private String state = "";

   public String getState() {
      return state;
   }

   public void setState(String state) {
      this.state = state;
      notifyObservers();
   }

   public void addObserver(Observer o) {
      observers.add(o);
   }

   public void removeObserver(Observer o) {
      observers.remove(o);
   }

   public void notifyObservers() {
      Iterator i = observers.iterator();
      while (i.hasNext()) {
         Observer o = (Observer) i.next();
         o.update(this);
      }
   }
}

The Client

import Subject;
import SubjectImpl;
import Observer;
import ObserverImpl;

public class Client {
   public static void main(String[] args) {
      Observer o = new ObserverImpl();
      Subject s = new SubjectImpl();
      s.addObserver(o);
      s.setState("New State");
   }
}

Strategy Design Pattern code example in Java

The Abstract Type (the dependency)

public interface SortInterface {
   public void sort(List l);
}

The Concrete Implementations of the Abstract Type

public class QuickSort implements SortInterface {
   public void sort(List l) { ... }
}

public class BubbleSort implements SortInterface {
   public void sort(List l) { ... }
}

The Dependent Abstract Type

import SortInterface;

public abstract class Sorter {
   private SortInterface si;

   public void setSorter(SortInterface si) {
      this.si = si; 
   }

   public SortInterface getSorter() {
      return this.si; 
   }

   public void doSort(List listToSort);
}

The Dependent Concrete Type

public class MySorter extends Sorter {

   public void doSort(List listToSort) {
      getSorter().sort(listToSort);
      // other processing here
   }
}

The Client

import MySorter;
import BubbleSort;

public class Client {
   MySorter mysorter = new MySorter();

   mysorter.setSorter(new BubbleSort());
   mysorter.doSort();

   mysorter.setSorter(new QuickSort());
   mysorter.doSort();
}