Behavioral patterns-Proxy proxies mode (Java)

Source: Internet
Author: User

Agent (embryonic form of AOP facets):

Preface: As the name implies is the use of a certain thing, something to allow authorization to transfer. Proxies are the equivalent of mediations (unlike the mediator pattern), which adds a bridge between the classes that were originally manipulated. However, the agent cannot modify the original target. For example: A person to buy a house, let the intermediary help to see a room, but intermediary can not be the original view of the matter changed to the car. He can make various requests and inquiries about the house.

Back to the point of view of the program, the caller will call some of the common class processing by the proxy class, the proxy class according to the requirements of the caller to meet what conditions can be called, what circumstances cannot be called, (seller commissioned intermediary 1 million above sell, 1 million below do not sell) to deal with before and after the packaging, But the proxy class cannot change the internal processing of the called Class (Coca-Cola China can modify the Coca-Cola packaging, but cannot change the Coca-Cola drink without authorization).

1. Static Proxy

2. Dynamic Agent

1. Static proxy: agent for the specified interface class, through the execution method before and after processing, to achieve the role of the agent. Because of the specified interface class, special handling of certain classes can be done.

1 /**2 * Static proxy, also known as decate mode3  * 4  * @authorDennyzhao5 * @date June 13, 20176  * @version1.07  */8  Public classAnimalproxyfactoryImplementsAnimalfactory {9     /**Ten * Serial Number One      */ A     Private Static Final LongSerialversionuid = -3421761900236678842l; -      -      the     Privateanimalfactory Animal; -      -      Publicanimalproxyfactory (animalfactory animal) { -          This. Animal =Animal; +     } - @Override +      Public intGetlegs () { ASystem.out.println ("Before....action"); at         intLegs =Animal.getlegs (); -System.out.println ("After....action"); -         returnlegs; -     } -  -}
View Code

Test main:

Static proxy
Rabit rabit = new Rabit ();
Animalproxyfactory proxyfactory = new Animalproxyfactory (rabit);
System.out.println (Proxyfactory.getlegs ());

Operation Result:

>>>before....action
>>>after....action
>>>4

2. Dynamic Proxy: The dynamic agent creates the proxy through the proxy class and invokes the method through Invokationhandler.

1  Packagepattern.creation.factory;2 3 ImportJava.io.FileInputStream;4 Importjava.io.FileNotFoundException;5 Importjava.io.IOException;6 ImportJava.lang.reflect.Proxy;7 Importjava.util.Properties;8 9 /**Ten * Dynamic Proxy mode One  *  A  * @authorDennyzhao - * @date June 13, 2017 -  * @version1.0 the  */ -  Public classProxyfactory { -     Private Static FinalString Class_name_path = "Pattern/classname.properties"; -@SuppressWarnings ("Unchecked") +      Public Static<T> T getinstance (String name)throwsillegalargumentexception, instantiationexception, illegalaccessexception{ -String ClassName =getclassname (name); +T result =NULL; A         Try { atClass Clazz =Class.forName (className); -result = (T) proxy.newproxyinstance (Clazz.getclassloader (), clazz.getinterfaces (),NewMyinvocationhandler (Clazz.newinstance ())); -}Catch(ClassNotFoundException e) { - e.printstacktrace (); -         } -         returnresult; in     } -  to     /** + * Get class name -      * @return the      */ *     Private Staticstring GetClassName (string name) { $Properties Pro =NewProperties ();Panax Notoginseng         Try { -String url = proxyfactory.class. getClassLoader (). GetResource (""). GetPath () +Class_name_path; thePro.load (Newfileinputstream (URL)); +}Catch(FileNotFoundException e) { A e.printstacktrace (); the}Catch(IOException e) { + e.printstacktrace (); -         } $         return(String) pro.get (name); $     } -}
View Code

Note *: The proxy is oriented towards the interface, so the delegated class needs to implement the specified interface.

result = (T) proxy.newproxyinstance (Clazz.getclassloader (), Clazz.getinterfaces (), New Myinvocationhandler ( Clazz.newinstance ()));

Clazz.getinterfaces (): If a clazz implements multiple interfaces, it is passed to the interface class here.

Myinvocationhandler implementation of the Invocationhandler interface, inside to implement an Invoke method, in this invoke method to fill in the processing.

Myinvocationhandler

Specialrequests for special classes can be handled through a radiological mechanism.

Test main:

Dynamic proxy, the embryonic approach to AOP facets
Animalfactory sheep = proxyfactory.getinstance ("sheep");
Sheep.getlegs ();

The practice of dynamic proxies, AOP facets
Plantfactory plum = proxyfactory.getinstance ("Plum");
Plum.getcolor ();

The practice of dynamic proxies, AOP facets
Animalfactory rabit0 = proxyfactory.getinstance ("Rabit");
Rabit0.getlegs ();

Results:

Before-------
Sheep has 4 legs ....
After-------
Before-------
Plum Green purple ....
After-------
Before-------
Rabbits are special.
After-------

Behavioral patterns-Proxy proxies mode (Java)

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.