Design Mode-proxy Mode
Scenario settings
Boy has a bunch of flowers to send to Girl, but I am sorry to send it, so I am looking for a Proxy to forward the flowers to Girl.
First, define the flower holder interface. All classes that implement this interface have the ability to send flowers:
interface FlowerKeeper{ public void sendFlower();}
Then define the Boy class, which can have flowers and the ability to send flowers (just not to send flowers in person ):
class Boy implements FlowerKeeper{ private String flowerName; Boy(String flower){ this.flowerName = flower; } @Override public void sendFlower() { System.out.println("I give you this flower"); }}
Next, Boy will look for a Proxy. This Proxy will also be able to have flowers (obtained from Boy) and the ability to send flowers:
Class Proxy implements FlowerKeeper {private FlowerKeeper boy = null; Proxy () {if (boy = null) boy = new Boy ("Tulip") ;}@ Override public void sendFlower () {System. out. println ("The Boy said:"); boy. sendFlower ();}}
Finally, this Proxy represents Boy and calls its ownsendFlowerThe method transfers the flowers to Girl (this class is not defined here, and the methods such as Girl confession may be held in the interface of FlowerKeeper ).
You can perform the following operations on the client:
public static void main(String[] args){ FlowerKeeper proxyFlowerKeeper = new Proxy(); proxyFlowerKeeper.sendFlower();}
For the sake of clarity, I define the Proxy object name as proxyFlowerKeeper. To achieve the Proxy's real purpose (to hide the inside), you can write it like this:
public static void main(String[] args){ FlowerKeeper boy = new Proxy(); boy.sendFlower();}
If there is another layer on the client,new Proxy();The details can not be exposed, and the outside world cannot know whether the boy is a Proxy or actually a Boy itself.
Agent Mode
The proxy mode is used to "proxy" the behavior of an object held by it. It may add some additional behavior on the basis of the original behavior, and at the same time, in the upper layer, there is no difference between calling these two behavior methods. Similar
No one knows you are a dog on the Internet.
The computer acts as a Proxy for a dog's keyboard operation. As long as the keyboard is correct, the words played by the root cannot be differentiated. Therefore, in the network end, Proxy (the other computer) it hides the objects and details it holds.