Proxy mode for design pattern Review

Source: Internet
Author: User

1. Java implementation

Interface Network
{
Public abstract void browser ();
}
Class real implements network
{
@ Override
Public void browser (){
// Todo auto-generated method stub
System. Out. println ("browsing information ");
}
}
Public class designpattern_proxy implements network {
Private Network newwork;
Designpattern_proxy (network Network)
{
This. newwork = network;
}
@ Override
Public void browser (){
// Todo auto-generated method stub
This. newwork. browser ();
}
Public static void main (string [] ARGs)
{
New designpattern_proxy (New Real (). browser ();
}
}

2. Dynamic proxy

Import java. Lang. Reflect. invocationhandler;
Import java. Lang. Reflect. method;
Import java. Lang. Reflect. proxy;

Interface Network
{
Public abstract void browser ();
}
Class real implements network
{
@ Override
Public void browser (){
// Todo auto-generated method stub
System. Out. println ("browsing information ");
}
}
// Inherit from invocationhandler override its invoke () method
  public class designpattern_dynmicproxy implements InvocationHandler{
private Object sub;
public designpattern_dynmicproxy(){}
public designpattern_dynmicproxy(Object obj)
{
this.sub = obj;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("before calling " + method);
method.invoke(sub, args);
System.out.println("after calling " + method);
return null;
}


public static void main(String [] args)
{
Real r = new Real();
InvocationHandler ds = new designpattern_dynmicproxy(r);
Class cls = r.getClass();
NetWork nw = (NetWork)Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(),ds);
nw.browser();
}


}

  

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.