Java design pattern: modifier pattern vs. proxy pattern

Source: Internet
Author: User
Tags comparison modifier


Decoration mode
Introduction & Java application scenarios
UML & code implementation
Android source code scenario
Proxy mode
Introduction & Java application scenarios
UML & code implementation
Android source code scenario
Similarities and differences between the decorator and agent modes
Comparison
Summary
Decoration mode

Introduction & Java application scenarios

Decorator mode (alias: Wrapper): A User's extended function that dynamically attaches responsibilities to objects. It is more flexible to use decorations than to use inheritance.
The I/O processing class we often see actually uses the modifier mode.

 

Public class DecoratorTest {
Public static void main (String [] args) throws IOException {
// Stream read files
DataInputStream dis = null;
Try {
Dis = new DataInputStream (
New BufferedInputStream (
New FileInputStream ("test.txt ")
                    )
);

// Read the file content
Byte [] bs = new byte [dis. available ()];
Dis. read (bs );
String content = new String (bs );
System. out. println (content );
} Finally {
Dis. close ();
        }
    }
}
UML & code implementation

 

Public interface Component {
Void operation ();
}

Public interface Decorator extends Component {
Void addedBehavior ();
}

Public class ConcreteComponent implements Component {
@ Override
Public void operation (){
System. out. println ("operation! ");
  }
}

Public class ConcreteDecorator implements Decorator {
Private Component decoratedComponent;

Public ConcreteDecorator (Component decoratedComponent ){
This. decoratedComponent = decoratedComponent;
  }

@ Override
Public void operation (){
System. out. println ("decorated operation! ");

DecoratedComponent. operation ();
  }

@ Override
Public void addedBehavior (){
System. out. println ("addedBehaviour! ");
  }
}

Public class Client {
Public static void main (String [] args ){
Component component = new ConcreteComponent ();
Component. operation ();

// Output:
// Operation!

Decorator decorator = new ConcreteDecorator (component );
Smart. operation ();
Smart. addedBehavior ();

// Output:
// Decorated operation!
// Operation!
// AddedBehaviour!
  }
}
Android source code scenario

HeaderViewListAdapter. java

Public class HeaderViewListAdapter implements WrapperListAdapter, Filterable {

Private final ListAdapter mAdapter;

Public HeaderViewListAdapter (ArrayList <ListView. FixedViewInfo> headerViewInfos,
ArrayList <ListView. FixedViewInfo> footerViewInfos,
ListAdapter adapter ){
MAdapter = adapter;

...
    }

...

Public int getCount (){
If (mAdapter! = Null ){
Return getFootersCount () + getHeadersCount () + mAdapter. getCount ();
} Else {
Return getFootersCount () + getHeadersCount ();
        }
    }

...

Public View getView (int position, View convertView, ViewGroup parent ){
// Header (negative positions will throw an IndexOutOfBoundsException)
Int numHeaders = getHeadersCount ();
If (position <numHeaders ){
Return mHeaderViewInfos. get (position). view;
        }

// Adapter
Final int adjPosition = position-numHeaders;
Int adapterCount = 0;
If (mAdapter! = Null ){
AdapterCount = mAdapter. getCount ();
If (adjPosition <adapterCount ){
Return mAdapter. getView (adjPosition, convertView, parent );
            }
        }

// Footer (off-limits positions will throw an IndexOutOfBoundsException)
Return mFooterViewInfos. get (adjPosition-adapterCount). view;
    }

...
ContextWrapper. java

 

Public class ContextWrapper extends Context {
Context mBase;

Public ContextWrapper (Context base ){
MBase = base;
    }

...
}
Proxy mode

Introduction & Java application scenarios

Proxy: provides a Proxy for an object and controls the reference to the original object by the Proxy object. This hides the specific information of an object from its customers. It is mainly used for remote proxy, virtual proxy, and protection proxy. The protection proxy can control access permissions.

The dynamic proxy provided by JDK uses the proxy mode. You can dynamically obtain the proxy class and call the proxy method.

Public interface Subject
{
Public void request ();
}

Public class RealSubject implements Subject
{
@ Override
Public void request ()
    {
System. out. println ("from real subject ");
    }
}

Public class MyInvocationHandler implements InvocationHandler
{
// Hold the reference of the proxy class
Private Subject real;

Public MyInvocationHandler (Subject real ){
This. real = real;
    }

Public Object invoke (Object proxy, java. lang. reflect. Method method,
Object [] args) throws Throwable {
// Execute the method of the proxy object
Object obj = method. invoke (real, args );
// Obj is the data returned by the method.
Return obj;
    }
}

Public class DynamicTest
{
Public static void main (String [] args)
    {
Subject real = new RealSubject ();
InvocationHandler h = new MyInvocationHandler (real );

// Obtain the array of all interfaces implemented by the proxy class. In this array, only Subject. class has one element.
Class [] interfaces = real. getClass (). getInterfaces ();

// Obtain the class loader
ClassLoader loader = h. getClass (). getClassLoader ();

// Obtain the dynamic proxy instance
Object s = java. lang. reflect. Proxy. newProxyInstance (loader, interfaces, h );

// Call the method through a proxy object
Subject sub = (Subject) s;
Sub. request ();
    }
}
UML & code implementation

 

Public interface Subject
{
Public void request ();
}

Public class RealSubject implements Subject
{
@ Override
Public void request ()
    {
System. out. println ("from real subject ");
    }
}

Public class Proxy implements Subject {
Private RealSubject realSubject;

Public Proxy (Subject realSubject ){
This. realSubject = realSubject;
    }

@ Override
Public void request (){
// The operation before the request
PreRequest ();

RealSubject. request ();

// The requested operation
PostRequest ();
    } 

Private void preRequest (){}

Private void postRequest (){}
}
Android source code scenario

Binder
WindowManagerImpl. java proxy WindowManagerGlobal. java
Similarities and differences between the decorator and agent modes

Comparison

UML

 

Decorator class and Proxy class

Public class ConcreteDecorator implements Decorator {
Private Component decoratedComponent;

Public ConcreteDecorator (Component decoratedComponent ){
This. decoratedComponent = decoratedComponent;
  }

@ Override
Public void operation (){
System. out. println ("decorated operation! ");

DecoratedComponent. operation ();
  }

@ Override
Public void addedBehavior (){
System. out. println ("addedBehaviour! ");
  }
}
Public class Proxy implements Subject {
Private RealSubject realSubject;

Public Proxy (Subject realSubject ){
This. realSubject = realSubject;
    }

@ Override
Public void request (){
// The operation before the request
PreRequest ();

RealSubject. request ();

// The requested operation
PostRequest ();
    } 

Private void preRequest (){}

Private void postRequest (){}
}
Summary

The modifier mode focuses on the dynamic addition of an object, while the proxy mode focuses on controlling access to the object.
Proxy mode hides the specific information of an object from its customers. When the proxy mode is used, we often create an object instance in a proxy class.
The purpose of the modifier mode is not to control access, but to expand functions. When we use the decorator mode, the common practice is to pass the original object as a parameter to the constructor of the decorator.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.