클래스 다이어그램
/** * 游戏者接口 * @author stone * */ public interface IGamePlayer { // 登录游戏 public void login(String user, String password); // 杀怪,网络游戏的主要特色 public void killBoss(); // 升级 public void upgrade(); }
/** * 游戏者 * @author stone * */ public class GamePlayer implements IGamePlayer { private String name = ""; // 通过构造函数传递名称 public GamePlayer(String _name) { this.name = _name; } // 打怪,最期望的就是杀老怪 public void killBoss() { System.out.println(this.name + " 在打怪!"); } // 进游戏之前你肯定要登录吧,这是一个必要条件 public void login(String user, String password) { System.out.println("登录名为" + user + " 的角色 " + this.name + "登录成功!"); } // 升级,升级有很多方法,花钱买是一种,做任务也是一种 public void upgrade() { System.out.println(this.name + " 又升了一级!"); } }
/** * 客户端 对被代理对象不可见 */ public class GamePlayerProxy implements IGamePlayer { private IGamePlayer gamePlayer = null;//被代理对象 // 通过构造函数传递要对谁进行代练 public GamePlayerProxy(String username) { this.gamePlayer = new GamePlayer(username); } // 代练杀怪 public void killBoss() { this.gamePlayer.killBoss(); } // 代练登录 public void login(String user, String password) { this.gamePlayer.login(user, password); } // 代练升级 public void upgrade() { this.gamePlayer.upgrade(); } }
/* * 客户端 对被代理对象不可见 */ public class GamePlayerProxy2 implements IGamePlayer { private IGamePlayer gamePlayer = null;//被代理对象 // 通过构造函数传递要对谁进行代练 public GamePlayerProxy2(String username) { this.gamePlayer = new GamePlayer(username); } // 代练杀怪 public void killBoss() { this.gamePlayer.killBoss(); } // 代练登录 public void login(String user, String password) { System.out.println("登录时间是:" + new Date().toLocaleString()); this.gamePlayer.login(user, password); } // 代练升级 public void upgrade() { this.gamePlayer.upgrade(); System.out.println("升级时间是:" + new Date().toLocaleString()); } }
인쇄:
/* * 客户端 对被代理对象不可见 */ public class GamePlayerProxy3 { private IGamePlayer gamePlayer; // 通过构造函数传递 被代练(代理)对象 public GamePlayerProxy3(IGamePlayer gamePlayer) { this.gamePlayer = gamePlayer; System.out.println("我是一名代练,我玩的角色是别人的,可以动态传递进来"); } public IGamePlayer getProxy() { return (IGamePlayer) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{IGamePlayer.class}, new MyInvocationHandler()); } private class MyInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("login")) { System.out.println("登录时间是:" + new Date().toLocaleString()); } if (method.getName().equals("upgrade")) { System.out.println("升级时间是:" + new Date().toLocaleString()); } method.invoke(gamePlayer, args); return null; } } }
위 내용은 Java 프록시(Proxy) 모드 구현에 대한 자세한 코드 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!