publicclassUserProxyimplementsIBaseFunction{privateRealUserrealUser;publicUserProxy(){if(this.realUser==null){this.realUser=newRealUser();}}@Overridepublicvoidtalk(){prepare();this.realUser.talk();finishWork();}privatevoidprepare(){System.out.println("Proxy is preparing...");}privatevoidfinishWork(){System.out.println("Proxy has done");}}
publicclassRobotProxyimplementsIRobot{privateIRobotrealRobot=null;publicRobotProxy(IRobot_robot){this.realRobot=_robot;}@Overridepublicvoidlogin(Stringname,Stringpassword){this.realRobot.login(name,password);}@Overridepublicvoidwalk(){System.out.println("Proxy prepares to walk");this.realRobot.walk();}@Overridepublicvoidfly(){System.out.println("Proxy prepares to fly");this.realRobot.fly();}}
publicclassRobotimplementsIRobot{privateStringname="";privateIRobotproxy=null;publicRobot(String_name){this.name=_name;}publicStringgetName(){returnname;}// get own proxypublicIRobotgetProxy(){this.proxy=newRobotProxy(this);returnthis.proxy;}privatebooleanisProxyWorking(){returnnull!=this.proxy;}@Overridepublicvoidlogin(Stringname,Stringpassword){if(isProxyWorking()){printf("user login: "+name);}else{outError();}}@Overridepublicvoidwalk(){if(isProxyWorking()){printf(this.name+" is walking.");}else{outError();}}@Overridepublicvoidfly(){if(isProxyWorking()){printf(this.name+" is flying.");}else{outError();}}privatevoidprintf(Stringmsg){System.out.println(msg);}privatevoidoutError(){printf(this.name+": DENY! Please use proxy!");}}
Wall-E: DENY! Please use proxy!
Wall-E: DENY! Please use proxy!
Wall-E: DENY! Please use proxy!
user login: Jerry
Proxy prepares to walk
Wall-E is walking.
Proxy prepares to fly
Wall-E is flying.
publicclassRobotProxyimplementsIRobot,IMessage{privateIRobotrealRobot=null;publicRobotProxy(IRobot_robot){this.realRobot=_robot;}@Overridepublicvoidlogin(Stringname,Stringpassword){this.realRobot.login(name,password);}@Overridepublicvoidwalk(){System.out.println("Proxy prepares to walk");this.realRobot.walk();}@Overridepublicvoidfly(){System.out.println("Proxy prepares to fly");this.realRobot.fly();say("Proxy: Flying high!");}@OverridepublicStringsay(Stringmsg){System.out.println(msg);returnmsg;}}
运行结果(部分)
user login: Jerry
Proxy prepares to walk
Wall-E is walking.
Proxy prepares to fly
Wall-E is flying.
Proxy: Flying high!