Java mix and potential type mechanisms

Source: Internet
Author: User

One, mixed type

①, definition

Second, how to realize the mixed type using Java

①, Agent ②, adorner mode ③, dynamic proxy mode

Iii. potential types of mechanisms

①, definition

Iv. compensation for potential type mechanisms in Java

①, using Reflection

Reply:

One, mixed type

is the ability of a class to mix multiple classes. When you want to modify something in a mixed class, these changes are applied to all types of the mix.

II. realization of mixed type

①, agent mechanism

Step: 1, create a mixed interface 2, create a specific implementation of the interface 3, create a mixed class, the class holds the mix.

First, create a mixed-type interface

 Public Interface fly{      void    Fly ();
Fly

Second, the specific implementation of creating an interface

 Public Implements fly{    publicvoid  Fly () {      System.out.println ("I can use swing to Fly");     }}    
Swing

Finally, create a concrete mixed-type class

 Public class Implements fly{    privatenew  Swing ();          Public void Fly () {        mswim.fly ();    }          Public void swim () {        System.out.println ("I can Swim");}    }
Duck

Cons: When using complex mixes, the amount of code increases sharply.

②, Adorner mode

Step: 1, create a decorated object (can be a class can also be an interface, preferably an interface here I use an interface) 2, create a decorated object inherit decorative interface 3, create an adorner (the adorner contains decorative objects)

1. Create a decorative interface

 Public Interface Basket {    void  Show ();}
Basket

2, inherit the decorative interface, for the decoration of the object

 Public class Implements basket{    @Override    publicvoid  Show () {        //  TODO auto-generated method Stub        System.out.println ("I am a Basket");}    }
Original

3. Creating adorners (Apple,banana,orange)

 Public classAppledecoratorImplementsbasket{PrivateBasket Mbasket;  PublicApple (Basket basket) {//TODO auto-generated Constructor stubMbasket =Basket; } @Override Public voidShow () {//TODO auto-generated Method Stubmbasket.show (); System.out.println ("Apple"); }}
Appledecorator
 Public classBananadecoratorImplementsbasket{PrivateBasket Mbasket;  PublicBanana (Basket basket) {//TODO auto-generated Constructor stubMbasket =Basket; } @Override Public voidShow () {//TODO auto-generated Method Stubmbasket.show (); System.out.println ("Banana"); }}
Bananadecorator

Other slightly

4, the use of decorative device

 Public class Main {    publicstaticvoid  Main (String[]args) {        new Original ();         New Apple (new Banana (new  Orange (original)));        Basket.show ();    }}
Main

Disadvantage: Only effect on the last layer of decoration.

③, dynamic Agent

Step: 1, create interface 2, create a specific implementation of the interface 3, create a proxy class 4, use the proxy class

①, creating interfaces

 Public Interface Business {    void  dosomething ();     void dosomeelse ();}
Business

②, implementing interfaces

 Public classRealobjectImplementsbusiness{@Override Public voiddosomething () {//TODO auto-generated Method Stubprintf ("Do some better things"); } @Override Public voidDosomeelse () {//TODO auto-generated Method Stubprintf ("Anything I can do it"); }         Public Static voidprintf (String str) {System.out.println (str); }}
Realobject

③, creating proxy classes

 Public classBusinessproxyImplementsinvocationhandler{PrivateObject Mdata;  Publicbusinessproxy (Object dataObject) {//TODO auto-generated Constructor stubMdata =DataObject; } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {//TODO auto-generated Method StubSystem.out.println ("No one thing I can do"); returnMethod.invoke (Mdata, args); }}
Businessproxy

④, start agent

 Public class Main {    publicstaticvoid  main (string[] args) {        new Realobject ();         = (business) proxy.newproxyinstance (business).  Classnew class[]{business.  Class},new  businessproxy (object));        Proxy.dosomething ();    }}
Main

Android potential type mechanism

1, what is called the latent type mechanism

In C + + and Python, you can call a method without knowing the type of the current class.

2. How to compensate for Java (reflection mechanism)

Step 1, build two classes, it has the same method

 Public class Typeone {    privateint data = 1;          Public void setData (int  data) {        this. data = data;    }           Public int GetData () {        return  data;    }}
Typeone
 Public class typetwo {    privateint data = 2;      Public void setData (int  data) {        this. data = data;    }           Public int GetData () {        return  data;    }}
Typetwo

2, using reflection call, the same method

 Public classMain { Public Static voidMain (string[] args) {//TODO auto-generated Method StubTypeone Typeone =NewTypeone (); Typetwo Typetwo=NewTypetwo (); //call the reflection method, implement different classes can call the same method by a methodGetData (Typeone);    GetData (Typetwo); }        //ways to implement reflection     Public Static voidgetData (Object type) {Class<?> C =Type.getclass (); Try {            //get a method called GetData ()method = C.getmethod ("GetData"); //Call this method            intdata = (int) Method.invoke (Type,NULL); //OutputSystem.out.println (Type.getclass (). Getsimplename () + "Data:" +data); } Catch(nosuchmethodexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}
Main

Java mix and potential type mechanisms

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.