Design Patterns


A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Patterns are formalized best practices that the programmer must implement in the application. 
Java design patterns are widely classified in to three categories
1.     Creational design patterns
a.     Singleton
b.     Factory Method
c.     Prototype
d.     Abstract Factory
e.     Builder
f.      Object Pool
2.     Structural design patterns
a.     Adapter
b.     Bridge
c.     Composite
d.     Decorator
e.     Façade
f.      Flyweight
g.     Private Class Data
h.     Proxy
3.     Behavioral design patterns
a.     Chain of responsibility
b.     Command
c.     Interpreter
d.     Iterator
e.     Mediator
f.      Memento
g.     Null Object
h.     Observer
i.      State
j.      Strategy
k.     Template method
l.      Visitor
Some of the important Design Patterns are explained below
1.    Singleton Pattern
Singleton is a Creational design patterns, Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private, so that you can restrict the creation of the object.
public class SingletonExample {
                  private static SingletonExample myObj;
                  static {
                                     myObj = new SingletonExample();
                  }
                  private SingletonExample() {
                  }
                  public static SingletonExample getInstance() {
                                     return myObj;
                  }
                  public void testSigleton() {
                                     System.out.println("Calling Singleton....");
                  }
                  public static void main(String a[]) {
                                     SingletonExample ms = getInstance();
                                     ms.testSigleton();
                  }
}

2.    Factory Pattern
The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
Examples: Currency, Database (Oracle, MSSql)Home (Flat, apartment, house …), Image Reader (Gif, Jpeg, PNG), Email (Batch, Real Time).
public interface Currency {
                  public String getCurrency();    
    public String getSymbol();
}
class India implements Currency {
                  @Override
                  public String getCurrency() {
                                     return "Rupee";
                  }
                  @Override
                  public String getSymbol() {
                                     return "Rs";
                  }
}
class USA implements Currency {
                  @Override
                  public String getCurrency() {
                                     return "Dollar";
                  }
                  @Override
                  public String getSymbol() {
                                     return "$";
                  }
}
 
public class CurrencyFactory {
                  public static Currency getCurrencyByCountry(String cnty) throws Exception {
                                     if ("IN".equalsIgnoreCase(cnty)) {
                                                       return new India();
                                     } else if ("USA".equalsIgnoreCase(cnty)) {
                                                       return new USA();
                                     }
                                     throw new Exception("Invalid country...");
                  }
 
                  public static void main(String a[]) {
                           Currency currency;
                           try {
                                     currency = CurrencyFactory.getCurrencyByCountry("USA");
                                     System.out.println("USA currency: " + currency.getCurrency());
                                     System.out.println("USA currency symbol: " + currency.getSymbol());
 
                                     currency = CurrencyFactory.getCurrencyByCountry("IN");
                                     System.out.println("Indian currency: " + currency.getCurrency());
                                     System.out.println("Indian currency symbol: " + currency.getSymbol());
                           } catch (Exception e) {
                                     e.printStackTrace();
                         }
                  }
}


3.    Prototype Design Pattern
The prototype pattern is a creational pattern. Prototype Pattern says that cloning of an existing object instead of creating new one and can also be customized as per the requirement.
Prototype.java
public interface Prototype {
                  public Prototype getClone();
}
 
EmployeeRecord.java
class EmployeeRecord implements Prototype {
                  private int id;
                  private String name, designation;
                  public EmployeeRecord() {
                                     System.out.println("   Employee Records of XYZ Corporation ");
                                     System.out.println("---------------------------------------------");
                                     System.out.println("Eid" + "\t" + "Ename" + "\t" + "Edesignation");
                  }
                  public EmployeeRecord(int id, String name, String designation) {
                                     this();
                                     this.id = id;
                                     this.name = name;
                                     this.designation = designation;
                  }
 
                  public void showRecord() {
                                     System.out.println(id + "\t" + name + "\t" + designation);
                  }
                  @Override
                  public Prototype getClone() {
                                     return new EmployeeRecord(id, name, designation);
                  }
}
 
PrototypeMain.java
public class PrototypeMain {
         public static void main(String[] args) {
                  int eid = 12345;
                  String ename = "Sathish";
                  System.out.print("\n");
                  String edesignation = "Technology Lead";
                  EmployeeRecord e1 = new EmployeeRecord(eid, ename, edesignation);
                  e1.showRecord();
                  System.out.println("\n");
                  EmployeeRecord e2 = (EmployeeRecord) e1.getClone(); // cloning
                  e2.showRecord();
         }
}
4.    Proxy Pattern
Proxy pattern is a Structural pattern. Proxy means an object representing another object.
Proxy Pattern "provides the control for accessing the original object".
So, we can perform many operations like hiding the information of original object, on demand loading etc.
OfficeInternetAccess.java

public interface OfficeInternetAccess {
                  public void grantInternetAccess();
}
 
DirectInternetAccess.java
public class DirectInternetAccess implements OfficeInternetAccess {
                  private String employeeName;
                  public DirectInternetAccess(String empName) {
                                     this.employeeName = empName;
                  }
                  @Override
                  public void grantInternetAccess() {
                  System.out.println("Internet Access granted for employee: " + employeeName);
                  }
}
 
ProxyInternetAccess.java
public class ProxyInternetAccess implements OfficeInternetAccess {
                  private String employeeName;
                  private DirectInternetAccess directAccess;
 
                  public ProxyInternetAccess(String employeeName) {
                                     this.employeeName = employeeName;
                  }
                  @Override
                  public void grantInternetAccess() {
                                     if (getRole(employeeName) > 4) {
                                                       directAccess = new DirectInternetAccess(employeeName);
                                                       directAccess.grantInternetAccess();
                                     } else {
                                     System.out.println("No Internet access granted. Your job level is below 5");
                                     }
                  }
                  public int getRole(String emplName) {
                                     // Check role from the database based on Name/id
                                     return 9;
                  }
}
 
ProxyPatternMain.java
public class ProxyPatternMain {
                  public static void main(String[] args) {
                                     OfficeInternetAccess access = new ProxyInternetAccess("Sathish");
                                     access.grantInternetAccess();
                  }
}


No comments:

Post a Comment