CSC/ECE 517 Fall 2012/ch2b 2w39 ka

From Expertiza_Wiki
Revision as of 18:02, 17 November 2012 by Ajain12 (talk | contribs)
Jump to navigation Jump to search

Introduction

Describe what Design pattern is and what are we going to discuss in this article.

Decorator Pattern

brief overview

Intent

Problem

Solution

Example

Implementation

Ruby

brief explanation and Sample Code:

     type the code here

Java

brief explanation and Sample Code:

     type the code here

Adapter Pattern

brief overview

Intent

Problem

Solution

Example

Implementation

Ruby

brief explanation and Sample Code:

     type the code here

Java

brief explanation and Sample Code:

     type the code here

Difference between Decorator Pattern and Adapter Pattern

Proxy Pattern

Sometimes we need the ability to control the access to an object. For example if we need to use only a few methods of some costly objects we'll initialize those objects when we need them entirely. Until that point we can use some light objects exposing the same interface as the heavy objects. These light objects are called proxies and they will instantiate those heavy objects when they are really need and by then we'll use some light objects instead.

Intent

"Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF<ref>"Gang of four"</ref>

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.

Solution

Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object.

Let's take a look at the diagram definition before we go into more detail.

As usual, when dealing with design patterns we code to interfaces. In this case, the interface that the client knows about is the Subject. Both the Proxy and RealSubject objects implement the Subject interface, but the client may not be able to access the RealSubject without going through the Proxy. It's quite common that the Proxy would handle the creation of the RealSubject object, but it will at least have a reference to it so that it can pass messages along.

Let's take a look at this in action with a sequence diagram.

As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.

There are many different flavours of Proxy, depending on it's purpose. You may have a protection proxy, to control access rights to an object. A virtual proxy handles the case where an object might be expensive to create, and a remote proxy controls access to a remote object.

You'll have noticed that this is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory.

Example

There are four common situations in which the Proxy pattern is applicable.

  • A virtual proxy is a placeholder for “expensive to create” objects.

The real object is only created when a client first requests/accesses the object. In place of a complex or heavy object use a skeleton representation. When an underlying image is huge in size, just represent it using a virtual proxy object and on demand load the real object. You feel that the real object is expensive in terms of instantiation and so without the real need we are not going to use the real object. Until the need arises we will use the virtual proxy.

  • A remote proxy provides a local representative for an object that resides in a different address space.

This is what the “stub” code in RPC and CORBA provides. Think of an ATM implementation, it will hold proxy objects for bank information that exists in the remote server. RMI is an example of proxy implmenetation for this type in java.

  • A protective proxy controls access to a sensitive master object.

The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request. You might be well aware of the proxy server that provides you internet. Saying more than provides, the right word is censores internet. The management feels its better to censor some content and provide only work related web pages. Proxy server does that job. This is a type of proxy design pattern. Lighter part of censor is, we search for something critical in Google and click the result and you get this page is blocked by proxy server. You never know why this page is blocked and you feel this is genuine. How do you overcome that, over a period you learn to live with it.

  • A smart proxy interposes additional actions when an object is accessed. Typical uses include:
    • Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
    • Loading a persistent object into memory when it’s first referenced,
    • Checking that the real object is locked before it is accessed to ensure that no other object can change it.

Implementation

Ruby

Let’s assume you need to log all method calls made to a bank Account object without changing the original Account definition. You can create a new class to wrap the Account object, log any method call then forward the request to the target object. Here’s a super simple bank Account.

   class Account

  def initialize(amount)
    @amount = amount
  end

  def deposit(amount)
    @amount += amount
  end

  def withdraw(amount)
    @amount -= amount
  end

  def balance
    @amount
  end

  def inspect
    puts "Amount: #{@amount}"
  end

end

and here’s our AccountLogger class.

class AccountLogger < BasicObject

  def initialize(amount)
    @operations = []

    @target = Account.new(amount)
    @operations << [:initialize, [amount]]
  end

  def method_missing(method, *args, &block)
    @operations << [method, args]
    @target.send(method, *args, &block)
  end

  def operations
    @operations
  end

end

The AccountLogger is our Proxy object. It doesn’t know anything about the target object, in fact it limits itself to log method calls and forward the request to the underlying @target using the method_missing hook.BasicObject actually prevents this issue by exposing a limited set of instance methods. Simply put, it copes with the problem from a different point of view: instead of taking a rich object and removing all the unnecessary methods, take a poor object and only define what you actually need.

Java

From JDK 1.3 java has direct support for implementing proxy design pattern. We need not worry on mainting the reference and object creation. Java provides us the needed utilities. Following example implementation explains on how to use java’s api for proxy design pattern.

public interface Animal {
 
   public void getSound();
 
}
public class Lion implements Animal {
 
  public void getSound() {
     System.out.println("Roar");
  }
 
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
 
public class AnimalInvocationHandler implements InvocationHandler {
  public AnimalInvocationHandler(Object realSubject) {
    this.realSubject = realSubject;
  }
 
  public Object invoke(Object proxy, Method m, Object[] args) {
    Object result = null;
    try {
      result = m.invoke(realSubject, args);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return result;
  }
 
  private Object realSubject = null;
}
import java.lang.reflect.Proxy;
 
public class ProxyExample {
 
  public static void main(String[] args) {
    Animal realSubject = new Lion();
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
        .getClassLoader(), realSubject.getClass().getInterfaces(),
        new AnimalInvocationHandler(realSubject));
    proxy.getSound();
  }
}

We have created a proxy handler that will be able to get the sound depending on the type of animal.

Difference between Decorator Pattern and Proxy Pattern

The two UML diagrams may confuse us. The two design patterns looks the same with each other. With Decorator Pattern, the decorator and the decoratee implement the same interfaces. With Proxy Pattern, the proxy class and the real class delegated implement the same interfaces. Furthermore, no matter which pattern is used, it is easy to add functions before or after the method of the real object. However, in fact, there are some differences between Decorator Pattern and Proxy Pattern. Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object. In other words, with Proxy Pattern, the proxy class can hide the detail information of an object from its client. Therefore, when using Proxy Pattern, we usually create an instance of object inside the proxy class. And when using Decorator Pattern, we typically pass the original object as a parameter to the constructor of the decorator.We can use another sentence to conclude thire differences:

With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively 
constructed at runtime.

Composite Pattern

When we want to represent part-whole hierarchy, use tree structure and compose objects. We know tree structure what a tree structure is and some of us don’t know what a part-whole hierarchy is. A system consists of subsystems or components. Components can further be divided into smaller components. Further smaller components can be divided into smaller elements. This is a part-whole hierarchy. Everything around us can be a candidate for part-whole hierarchy. Human body, a car, a computer, lego structure, etc. A car is made up of engine, tyre,etc. Engine is made up of electrical components, valves, etc. Electrical components is made up of chips, transistor,etc. Like this a component is part of a whole system. This hierarchy can be represented as a tree structure using composite design pattern.

Intent

“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.” is the intent by GoF.

Problem

Application needs to manipulate a hierarchical collection of “primitive” and “composite” objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the “type” of each object before attempting to process it is not desirable.

Solution

The figure below shows a UML class diagram for the Composite Pattern:

  • Component - Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders.
  • Leaf - Leafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSize methods which are related to the Component interface.
  • Composite - A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components.
  • Client - The client manipulates objects in the hierarchy using the component interface.

A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn't matter if the node is a composite or a leaf.

Example

  • GUI toolkits:

For example, Java SWT (Standard Widget Toolkit). If you want to apply a theme for a dialog, you need to apply the theme for the dialog and all its child components. A child can be a composite or a widget itself. If it is a widget, there is no child for that, and the theme needs to be applied only for the widget. But if it is a composite, we need to apply the theme for all its children. Now again, a child can be a widget or a composite. The loop continues until it covers all child widgets.

  • Destruction of objects in C++:

Take any OO language without a garbage collector. Just imagine you have a data structure like tree. Each object has a reference only to his children and the client is aware of only the root node object. How will you destroy all the objects, leaving no memory leak? It is only a couple of lines of code that takes to destroy the complete code. Kill a node = Kill all its children and then kill yourself. Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.

In both the above mentioned cases using a composite pattern based recursion is a wise approach.

Implementation

Ruby

Use this in cases where your design seems to have a hierarchy. The hierarchy can be established by data/logic i.e Tasks & SubTasks, Parts & SubParts.

     class Part
  def initialize name
    @name = name
  end
  def weight
    0
  end
end

class Hand < Part
  def initialize
    super("Hand")
    @children = []
    5.times {add_child Finger.new}
  end

  def weight #component object
    weight  = 5
    @children.each { |c| weight += c.weight }
    weight
  end

  def add_child child
    @children << child
  end
end

class Finger < Part
  def initialize
    super("Finger")
  end

  def weight #Leaf object
    1
  end
end
hand = Hand.new
puts hand.weight #7

Note here that the complex weight methods have been implemented in the component class and not the leaf class.

Java

Here is the sample code that implements composite pattern.

    public class Block implements Group {
 
    public void assemble() {
        System.out.println("Block");
    }
}
public interface Group {
    public void assemble();
}
import java.util.ArrayList;
import java.util.List;
 
public class Structure implements Group {
  // Collection of child groups.
  private List<Group> groups = new ArrayList<Group>();
 
  public void assemble() {
    for (Group group : groups) {
      group.assemble();
    }
  }
 
  // Adds the group to the structure.
  public void add(Group group) {
    groups.add(group);
  }
 
  // Removes the group from the structure.
  public void remove(Group group) {
    groups.remove(group);
  }
}
public class ImplementComposite {
   public static void main(String[] args) {
          //Initialize three blocks
          Block block1 = new Block();
          Block block2 = new Block();
          Block block3 = new Block();
 
          //Initialize three structure
          Structure structure = new Structure();
          Structure structure1 = new Structure();
          Structure structure2 = new Structure();
 
          //Composes the groups
          structure1.add(block1);
          structure1.add(block2);
 
          structure2.add(block3);
 
          structure.add(structure1);
          structure.add(structure2);
 
          structure.assemble();
      }
}

Difference between Decorator Pattern and Composite Pattern

They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern. The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity. Essence is that all elements in your composite structure have the same interface even though some are leafs and others are entire structures. User interfaces often use this approach to allow easy composability. However, The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity. For example, you might use a decorator to add logging output on the usage of the contained element without changing any behavior of the contained element.

Conclusion

This article makes an attempt to explain the concept of Reflection in Object Oriented Programming. The article mentions the different approaches to reflection in Ruby and other languages.It mentions the usage of Reflections and the advantages and disadvantages of using Reflection. A follow up to this article would be to study the concept of Metaprogramming.

References

<references />

Additional Reading