Five ‘s Weblog

November 17, 2007

The differences between Decorator Pattern and Proxy Pattern

Filed under: Five's thought — by powerdream5 @ 9:38 pm
Tags: ,

       Firstly, Let’s look at the following two UML diagrams which describes the basic implementation of Decorator Pattern and Proxy Pattern respectively.

11_17_2_2007.jpg

11_17_3_2007.jpg

        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 abject 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.

//Proxy Pattern
public class Proxy implements Subject{

       private Subject subject;
       public Proxy(){
             //the relationship is set at compile time
            subject = new RealSubject();
       }
       public void doAction(){
             ….
             subject.doAction();
             ….
       }
}

//client for Proxy
public class Client{
        public static void main(String[] args){
             //the client doesn’t know the Proxy delegate another object
             Subject subject = new Proxy();
             …
        }
}
//Decorator Pattern
public class Decorator implements Component{
        private Component component;
        public Decorator(Component component){
            this.component = component
        }
       public void operation(){
            ….
            component.operation();
            ….
       }
}

//client for Decorator
public class Client{
        public static void main(String[] args){
            //the client designate which class the decorator decorates
            Component component = new Decorator(new ConcreteComponent());
            …
        }
}

11_17_4_2007.jpg

Advertisements

Create a free website or blog at WordPress.com.