Java design pattern: proxy pattern
Package proxy; public class Client {/*** test class Client ** the proxy mode generally requires an interface to be defined so that both the proxy class and the proxy class can implement this interface, * In this way, the proxy class method can be used where the method of the proxy class is used, and the * method of the proxy class actually calls the method of the proxy class ** example: zeng xianer wanted to give a gift to the goddess Yifei, but he was sorry, so he had to ask Yifei's * younger brother Zhan Bo to give a present instead. * @ Author wl */public static void main (String [] args) {Girl girl = new Girl (); girl. setName (""); Sender ZengXianEr = new Sender (girl); // Proxyer: Zeng xianer Proxyer ZhanBo = new Proxyer (ZengXianEr); // Proxy: zhan Bo ZhanBo. sendDoll (); // The proxy class sends dolls. Actually, the sendDoll method called by the proxy Zeng xianer is the same as ZhanBo. sendFolwer (); ZhanBo. sendChocolate ();}}
Package proxy;/*** proxy class and public interface of the proxy class * @ author wl **/public interface SendGift {public abstract void sendDoll (); public abstract void sendFolwer (); public abstract void sendChocolate ();}
Package proxy;/*** is the proxy class, which implements public interfaces. This method in it is * Self-specific implementation, and has nothing to do with other classes, this is the difference between it and the proxy class * @ author wl **/public class Sender implements SendGift {Girl girl Girl; public Sender (girl Girl) {this. girl = girl;} @ Overridepublic void sendDoll () {System. out. println (girl. getName () + "send you doll") ;}@ Overridepublic void sendFolwer () {System. out. println (girl. getName () + "send you flowers") ;}@ Overridepublic void sendChocolate () {System. out. println (girl. getName () + "send you chocolate ");}}
Package proxy;/*** proxy class, which implements public interface methods, but the specific implementation is to call the method of the agent, * For example, if Zhan Bo does not call the method of sending gifts to Zeng xianer, the agent, but implements it on his own, * Zhan Bo will give a gift to yi fei, it has nothing to do with Zeng xianer, the agent. * @ Author wl **/public class Proxyer implements SendGift {Sender sender; public Proxyer (Sender sender) {this. sender = sender ;}@ Overridepublic void sendDoll () {sender. sendDoll () ;}@ Overridepublic void sendFolwer () {sender. sendFolwer () ;}@ Overridepublic void sendChocolate () {sender. sendChocolate ();}}
Package proxy;/*** recipient * @ author wl **/public class Girl {private String name; public String getName () {return this. name;} public void setName (String name) {this. name = name ;}}
Output:
Yifei delivers your doll
Yifei sends you flowers
Yifei sends you chocolate