DesignPattern_Java: Proxy Pattern
Proxy mode Proxy Pattern delegation mode Provide a surrogate or placeholder for another object to control access to it. Provides a Proxy for other objects to control access to this object. Abstract topic role (Subject): this role is a common interface between a real topic and a proxy topic, so that a proxy topic can be used wherever a real topic can be used.
Package com. DesignPattern. Structural. Proxy; public interface Subject {// define a request method public void request ();}
Proxy Subject: it is also called a delegate class. This role controls the reference to a real topic and creates or deletes a real topic object as needed, in addition, pre-processing and post-processing are performed before and after real topic roles are processed.
Package com. designPattern. structural. proxy; public class ProxySubject implements Subject {private Subject subject; public ProxySubject (Subject subject) {this. subject = subject;} // request Method @ Override public void request () {this. beforeRequest (); subject. request (); this. afterRequest ();} // the operation before the request is private void beforeRequest () {// preprocessing} // The operation after the request is private void afterRequest () {// aftercare }}
Real Subject: this role is also called a delegated role and a proxy role. It is the specific performer of the business logic.
Package com. DesignPattern. Structural. Proxy; public class RealSubject implements Subject {@ Override public void request () {// business processing logic System. out. println (realSubject request );}}
Proxy mode instance IGamePlayer. java
Package com. DesignPattern. Structural. Proxy; public interface IGamePlayer {public void killBoss (); // kill the monster public void upGrade (); // upGrade}
GamePlayer. java
package com.DesignPattern.Structural.Proxy;public class GamePlayer implements IGamePlayer { private String name = ; public GamePlayer(String name) { this.name = name; } @Override public void killBoss() { System.out.println(this.name + killBoss); } @Override public void upGrade() { System.out.println(this.name + upgrade level 1); }}
GamePlayerProxy. java
Package com. designPattern. structural. proxy; import java. util. date; public class GamePlayerProxy implements IGamePlayer {private IGamePlayer player = null; public GamePlayerProxy (IGamePlayer player) {this. player = player;} // record the hitting time private void log () {System. out. println (hitting time + new Date (). toString () ;}@ Override public void killBoss () {this. log (); player. killBoss () ;}@ Override public void upGrade () {pl Ayer. upGrade (); this. count () ;}// calculate the upgrade time private void count () {System. out. println (upGrade cost time !); }}
ClientDemo. java
package com.DesignPattern.Structural.Proxy;public class ClientDemo { public static void main(String[] args){ IGamePlayer player=new GamePlayer(Tom); IGamePlayer proxy=new GamePlayerProxy(player); proxy.killBoss(); proxy.upGrade(); }}