CSC/ECE 517 Fall 2012/ch2b 2w37 ms

From PG_Wiki
Jump to: navigation, search

Adapter pattern and the related patterns (Bridge, Decorator, Facade)

The adapter design pattern allows the user to make changes to the existing class with other class libraries without changing the code for the existing class. [1] The Bridge, Decorator and the Facade pattern look somewhat similar to the adapter pattern but their intent is different and that intent is what separates the above patterns from each other.

Contents

Adapter Pattern

Adapter pattern plays an important role when you want to incompatible interfaces to work together. It is generally used for third party code or code that we cannot modify. If such code uses an interface which is different from the interface we wish to use, adapter is the answer to the problem.The real world example for an adapter pattern is the travel power adapter.Different countries have different socket and plug configuration. So you can use an adapter to fit a plug into a socket that initially was not possible due to different interface designs. [2]

Implementattion

Adapter implementation using inheritance

This method can be used when you have incompatible method that needs to be used in other class. Using inheritance a "is-a" relationship is established between the base class and super class. The new compatible methods will be contained in the inherited adapter class. [2]

public class CylindricalSocket {
  public String supply(String cylinStem1, String cylinStem1) {
    System.out.println("Power power power...");
  }
}

public class RectangularAdapter extends CylindricalSocket {
  public String adapt(String rectaStem1, Sting rectaStem2) {
    //some conversion logic
    String cylinStem1 = rectaStem1;
    String cylinStem2 = rectaStem2;
    return supply(cylinStem1, cylinStem2);
  }
}

public class RectangularPlug {
  private String rectaStem1;
  private String rectaStem2;
  public getPower() {
    RectangulrAdapter adapter = new RectangulrAdapter();
    String power = adapter.adapt(rectaStem1, rectaStem2);
    System.out.println(power);
  }
}
Adapter implementation using composition

The other approach is to have a base class as an attribute in the adapter class. This creates an "has-a"relationship between the base class and the sub class. [2]


public class CylindricalSocket {
  public String supply(String cylinStem1, String cylinStem1) {
    System.out.println("Power power power...");
  }
}

public class RectangularAdapter {
  private CylindricalSocket socket;

  public String adapt(String rectaStem1, Sting rectaStem2) {
    //some conversion logic
    socket = new CylindricalSocket();
    String cylinStem1 = rectaStem1;
    String cylinStem2 = rectaStem2;
    return socket.supply(cylinStem1, cylinStem2);
  }
}

public class RectangularPlug {
  private String rectaStem1;
  private String rectaStem2;
  public getPower() {
    RectangulrAdapter adapter = new RectangulrAdapter();
    String power = adapter.adapt(rectaStem1, rectaStem2);
    System.out.println(power);
  }
}
Composition or inheritance to implement Adapter Pattern?


Adapter pattern in Java Library

Bridge Pattern

As stated by GoF a bridge design patterns intent is to “Decouple an abstraction from its implementation so that the two can vary independently”. [3]

Elements of Bridge Design Pattern

For example: A Vehicle class which has a manufacture method.

For example, a Car class or a Bike class which has a manufacture method which is more refined than the Vehicle class.

For example, the Workshop class acts as an implementor with the work() method.

For example the Produce and the Assemble class with the work() method provides the concrete implementation. [1][3]


UML Diagram for Bridge-Pattern [3]
Without Bridge-Pattern [3]
With Bridge-Pattern [3]









Example code for Bridge pattern

Vehicle Interface [3]

// abstraction in bridge pattern
abstract class Vehicle {
  protected Workshop workShop1;
  protected Workshop workShop2;

  protected Vehicle(Workshop workShop1, Workshop workShop2) {
    this.workShop1 = workShop1;
    this.workShop2 = workShop2;
  }

  abstract public void manufacture();
}

Car class [3]

//Refine abstraction 1 in bridge pattern
public class Car extends Vehicle {

  public Car(Workshop workShop1, Workshop workShop2) {
    super(workShop1, workShop2);
  }

  @Override
  public void manufacture() {
    System.out.print("Car ");
    workShop1.work();
    workShop2.work();

  }

}

Bike Class [3]

// Refine abstraction 2 in bridge pattern
public class Bike extends Vehicle {

  public Bike(Workshop workShop1, Workshop workShop2) {
    super(workShop1, workShop2);
  }

  @Override
  public void manufacture() {
    System.out.print("Bike ");
    workShop1.work();
    workShop2.work();
  }

}

Workshop Interface [3]

 // Implementor for bridge pattern
public interface Workshop {
  abstract public void work();
}

Produce Class [3]

// Concrete implementation 1 for bridge pattern
public class Produce implements Workshop {

  @Override
  public void work() {
    System.out.print("Produced");
  }

}

Assemble Class [3]

  //Concrete implementation 2 for bridge pattern
public class Assemble implements Workshop {

  @Override
  public void work() {
    System.out.println(" Assembled.");
  }

}

Demonstration of bridge design [3]

public class BridgePattern {

  public static void main(String[] args) {

    Vehicle vehicle1 = new Car(new Produce(), new Assemble());
    vehicle1.manufacture();
    Vehicle vehicle2 = new Bike(new Produce(), new Assemble());
    vehicle2.manufacture();

  }
}

Output:

Car Produced Assembled.
Bike Produced Assembled.
Bridge vs Adapter pattern

While the two patterns may seem similar according to the GoF- "Adapter makes things work after they're designed; Bridge makes them work before they are. [GoF, p219]".[1]

The adapter pattern is useful when we have code that is either third party or maybe in house, over which we do not have any control and such code do not fit with the interface that we wish to use. In such a case we use either of two (delegation or inheritance) model of the adapter pattern to change the existing classes (which do not fit our interface) and cast them to our desired interface.

The bridge pattern on the other hand is something we implement upfront on classes that have orthogonal hierarchies. It provides a way to decouple the interface and the implementation in such a way that you don't get an insane number of classes. In bridge pattern we usually deal with classes that vary in their implementations a lot and we want to incorporate the functionality of the implementation classes as much as possible. Bridge pattern is many times implemented with the help adapter pattern to give the orthogonal hierarchies a common interface.

For example,we have a FileReader interface with two implementations. One that reads file from windows system and one that read Files from Linux systems. Now there are two more interface say MemoryMappedFiles and RADFiles. Now bridge pattern will help you in not having to write four classes MemoryMappedWindowsFileReader, MemoryMappedLinuxFileReader, RADWindowsFileReader, RADWindowsFileReader.

Use adapter pattern to adapt MemoryMappedFiles and RADFiles to a common interface (assuming both implementations have SpecialFile interface in common). Also WindowsFileReader and LinuxFileReader are two implementations of the FileReader interface.

public interface CrossPlatformSpecialPurposeFileReader{
  public void readFile(); // used for adapting
 
}
SpecialWindowsFileReader extends WindowsFileReader implements CrossPlatformSpecialPurposeFileReader{
  SpecialFile specialFile;
  public SpecialWindowsFileReader(SpecialFile specialFile){
     this.specialFile = specialFile;
  }
  public void readFile(){
     byte fileBytes[] = this.read(); // read platform specific and convert to bytes
     this.specialFile(fileBytes) // decouples from the filesystem specifics.
  }
}
SpecialLinuxFileReader extends LinuxFileReader implements CrossPlatformSpecialPurposeFileReader{
  SpecialFile specialFile;
  public SpecialLinuxFileReader(SpecialFile specialFile){
     this.specialFile = specialFile;
  } 
  public void readFile(){
     byte fileBytes[] = this.read(); // read platform specific and convert to bytes
     this.specialFile(fileBytes) // decouples from the filesystem specifics.
  }
}

Bridge Pattern

public class Bridge{
  public static void main(String args[]){
    CrossPlatformSpecialPurposeFileReader specialFiles[] = new CrossPlatformSpecialPurposeFileReader[2];
    specialFiles[0] = new SpecialWindowsFileReader(new MemoryMappedFiles());
    specialFiles[1] = new SpecialLinuxFileReader(new RADFiles());
    // deouples two orthogonal implementations under one interface.
    for(CrossPlatformSpecialPurposeFileReader reader : specialFiles){
           reader.readFile();     
    }   
  }
}

Decorator Pattern

The decorator pattern adds responsibility to an object dynamically. The decorator design pattern is used to extend the behavior of an object dynamically. In order to extend the behavior we have to construct an wrapper around the object. Inheritance is not feasible since it is applied to an entire class. With the decorator pattern it is possible to select any particular instance and modify its behavior leaving the other instances unmodified.[1][4]

UML Diagram for Decorator-Pattern [4]

Implementation of Decorator Pattern

First start with the interface which will be used by the class having the decoration design. The example below explains how you first create a base ice cream and then decorate that ice cream by adding new toppings. The added topping changes the behavior of that ice cream. i.e. it gives the ice cream more taste.

The interface below contains an makeIcecream() method which has not been implemented yet.[4]

public interface Icecream {
 public String makeIcecream();
} 

The SimpleIceCream Class provides an implementation to the makeIcecream() method. This is the class which acts as a base class on which decorations will be added.[4]

public class SimpleIcecream implements Icecream {

 @Override
 public String makeIcecream() {
   return "Base Icecream";
 }

}

The class below is the crux of the design pattern. Here is where all the Decoration is actually provided to an instance of the object.It contains an attribute of type Icecream. Once the instance is assigned using the constructor the instance method will be invoked. [4]

abstract class IcecreamDecorator implements Icecream {

 protected Icecream specialIcecream;

 public IcecreamDecorator(Icecream specialIcecream) {
   this.specialIcecream = specialIcecream;
 }

 public String makeIcecream() {
   return specialIcecream.makeIcecream();
 }
}

The NuttyDecorator and HoneyDecorator are the two concrete classes that implement the abstract decorator class IcecreamDecorator. [4]

public class NuttyDecorator extends IcecreamDecorator {

 public NuttyDecorator(Icecream specialIcecream) {
   super(specialIcecream);
 }

 public String makeIcecream() {
   return specialIcecream.makeIcecream() + addNuts();
 }

 private String addNuts() {
   return " + cruncy nuts";
 }
}
public class HoneyDecorator extends IcecreamDecorator {

 public HoneyDecorator(Icecream specialIcecream) {
   super(specialIcecream);
 }

 public String makeIcecream() {
   return specialIcecream.makeIcecream() + addHoney();
 }

 private String addHoney() {
   return " + sweet honey";
 }
}


Decorator pattern in Java Library

Adaptor Pattern vs Decorator Pattern

Facade Pattern

Without Facade-Pattern [6]
With Facade-Pattern [6]

GoF defines a facade design pattern as a pattern which , “Provides a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.” [1][6]


Consider a software component. In order to get the job done this component might have to expose a of interfaces so that it can interact with other components in a process flow. Facade pattern simplifies this process by providing an unified interface. It builds an additional layer of abstraction over the existing abstract layer to simplify the process.


A microwave oven is made up of components like trasnformer, capacitor, magnetron, waveguide and some small other components. For a microwave to work all these different components needs to be executed in a sequence. If all these components had separate interfaces it would have been hard and complicated.Hence oven provides you buttons which can be considered as a facade. When you click on single button the job is done. That single button works as an abstraction layer between the user and the internal components. [6]

Facade Pattern in java library

ExternalContext Class in java performs cookie management by using an facade pattern. It makes use of components such as HttpSession,ServletContext, javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse. [6]

Facade Pattern vs Adapter Pattern

Conclusion

References

  1. 1.0 1.1 1.2 1.3 1.4 http://c2.com/cgi/wiki?GangOfFour
  2. 2.0 2.1 2.2 2.3 2.4 http://javapapers.com/design-patterns/adapter-pattern/
  3. 3.00 3.01 3.02 3.03 3.04 3.05 3.06 3.07 3.08 3.09 3.10 3.11 3.12 http://javapapers.com/design-patterns/bridge-design-pattern/
  4. 4.0 4.1 4.2 4.3 4.4 4.5 4.6 4.7 http://javapapers.com/design-patterns/decorator-pattern/
  5. http://sourcemaking.com/design_patterns/decorator
  6. 6.0 6.1 6.2 6.3 6.4 6.5 http://javapapers.com/design-patterns/facade-design-pattern/
  7. http://snehaprashant.blogspot.com/2008/08/adapter-pattern.html
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox