Proxy refers to the unrelated code that is combined to run at runtime. This improves the maintainability of the program and completely isolates the Business Code from the server code. This example uses person. -- the next article is about writing dynamic proxies, AOP ..
Person interface:
Public
Interface
Iperson {
Public void sleep ();
Public void walk ();
}
Person implementation class:
Public
Class personimp implements
Iperson {
Public
Void sleep (){
System. Out
. Println ("sleep..."); // Business Code, such as inserting data into the database, but not including transactions
}
Public
Void walk (){
System. Out
. Println ("walk..."); // Business Code
For example, inserting data into the database, but not including transactions
}
}
The person proxy class implements the iperson interface:
Public
Class proxyperson implements
Iperson {
Private
Iperson person;
Public
Void setperson (iperson person ){
This. Person = person;
}
Public
Proxyperson (iperson person ){
Super
();
This. Person = person;
}
Public
Void sleep (){
System. Out
. Println ("befor sleep"); // Service Code, such as opening a transaction
Person. Sleep (); // call the sleep method of personimp
System. Out
. Println ("after sleep"); // Service Code, such as transaction commit and rollback
}
Public
Void walk (){
System. Out
. Println ("befor walk"); // Service Code, such as opening a transaction
Person. Walk (); // call the Walk Method of personimp
System. Out
. Println ("after walk"); // Service Code, such as transaction commit and rollback
}
}
Test:
Public
Class staticproxytest {
Public
Static
Void main (string [] ARGs ){
Iperson person = new proxyperson (New personimp (); // Since proxyperson and personimp both implement the iperson interface, you can use iperson to receive the message and then call the start method.
Person. Sleep (); // actually called the sleep method in proxyperson
Person. Walk (); // actually the sleep method in the proxyperson
}
}
Effect:
Befor sleep
Sleep...
After sleep
Befor walk
Walk...
After walk