This article is intended for your own understanding and may cause errors. If there is any error, please point it out.
In programming, developers may call methods or classes that cannot be directly accessed by themselves. They do not want to expose classes to users directly. At this time, they can generally develop a called class proxy, then, you can control the access to the actual class by controlling the access to the proxy class. This proxy class also recognizes these two classes as a bridge between these two classes. The proxy mode provides a proxy for other objects to control access to this object.
The following describes this mode through analogy. A gg wants to pursue a MM, but she does not know it. At this time, she finds a man-in-the-middle who knows the two men. This GG wants to send this MM doll, chocolate, flowers, but he does not dare, so he finds a man-in-the-middle who also sends dolls, chocolate, and flowers, but the actual execution is the MM method.
Next, let's take a look at the class diagram and code.
[Java]
Package loveproxy;
Interface IGiveGift {
Void GiveDolls ();
Void GiveFlowers ();
Void GiveChocolate ();
}
[Java]
Package loveproxy;
Class Pursuit implements IGiveGift {
SchoolGirl mm;
Public Pursuit (SchoolGirl mm ){
This. mm = mm;
}
@ Override
Public void GiveDolls (){
System. out. println (mm. getName () + ", give you a doll ");
}
@ Override
Public void GiveFlowers (){
System. out. println (mm. getName () + ", send you flowers ");
}
@ Override
Public void GiveChocolate (){
System. out. println (mm. getName () + ", send you chocolate ");
}
}
[Java]
Package loveproxy;
Class Proxy implements IGiveGift {
Pursuit gg;
Public Proxy (SchoolGirl mm ){
This. gg = new Pursuit (mm );
}
@ Override
Public void GiveDolls (){
Gg. GiveDolls ();
}
@ Override
Public void GiveFlowers (){
Gg. GiveFlowers ();
}
@ Override
Public void GiveChocolate (){
Gg. GiveChocolate ();
}
}
[Java]
Package loveproxy;
Class SchoolGirl {
Private String name;
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
}
[Java]
Package loveproxy;
Public class Test {
/**
* @ Param args
*/
Public static void main (String [] args ){
SchoolGirl mm = new SchoolGirl ();
Mm. setName ("Big Beauty ");
Proxy proxy = new Proxy (mm );
Proxy. GiveDolls ();
Proxy. GiveFlowers ();
Proxy. GiveChocolate ();
}
}
Running result:
[Java]
Big Beauty, give you a doll
Big Beauty, send you flowers
Big Beauty, give you chocolate
The proxy class implements the same interface as the proxy class and contains a reference to the proxy class. In this way, you can use the proxy class to replace the entity class for operation. We can add some corresponding logic or corresponding permission verification in the proxy class.
Author: mengxiangyue