设计模式--5.3 代理模式-强制代理
1 .强制代理
(1)强制代理是调用者直接调用真实角色,而不用关心代理类是否存在。其代理的产生是由真实角色决定的。
(2) 通过真实角色,查找代理角色;再通过代理角色,调真实角色的方法
2.代码
(1)抽象类,多了一个getProxy方法
package com.design.代理模式.强制代理; public interface IGamePlayer { void login(String username , String pwd); void killBoss(); void upgrade(); IGamePlayer getProxy(); }
(2)真实角色
package com.design.代理模式.强制代理; public class GamePlayer implements IGamePlayer { private String name = ""; private IGamePlayer proxy = null; public GamePlayer(String name) { super(); this.name = name; } @Override public IGamePlayer getProxy(){ this.proxy = new GamePlayerProxy(this); return this.proxy; } @Override public void login(String username, String pwd) { if(this.isProxy()){ System.out.println("name:" + name +" login...."); }else{ System.out.println("请使用代理"); } } @Override public void killBoss() { if(this.isProxy()){ System.out.println("name:" + name +" killBoss...."); }else{ System.out.println("请使用代理"); } } @Override public void upgrade() { if(this.isProxy()){ System.out.println("name:" + name +" upgrade...."); }else{ System.out.println("请使用代理"); } } private boolean isProxy(){ if(this.proxy == null){ return false; }else{ return true; } } }
(3)代理类
package com.design.代理模式.强制代理; import java.util.Date; public class GamePlayerProxy implements IGamePlayer { private IGamePlayer gamePlayer = null; public GamePlayerProxy(IGamePlayer gamePlayer) { super(); this.gamePlayer = gamePlayer; } @Override public void login(String username, String pwd) { System.out.println(username+"开始登录"); this.gamePlayer.login(username, pwd); System.out.println(username+"登录完成"); } @Override public void killBoss() { System.out.println("开始打怪" + new Date()); this.gamePlayer.killBoss(); Thread.currentThread(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("打怪结束" + new Date()); } @Override public void upgrade() { this.gamePlayer.upgrade(); System.out.println("恭喜升级完成"); } @Override public IGamePlayer getProxy() { return this; } }
(4)场景类
package com.design.代理模式.强制代理; public class Client { public static void main(String[] args) { // 1.不使用代理,看结果,只能打印请使用代理 IGamePlayer gp1 = new GamePlayer("lvyf"); gp1.login("lvyf", "123"); gp1.killBoss(); gp1.upgrade(); // 2.使用代理类,还是不行 IGamePlayer gp2 = new GamePlayer("lvyf"); IGamePlayer gp3 = new GamePlayerProxy(gp2); gp3.login("lvyf", "123"); gp3.killBoss(); gp3.upgrade(); // 3. 通过真实角色,查找代理角色;再通过代理角色,调真实角色的方法 IGamePlayer gp4 = new GamePlayer("lvyf"); IGamePlayer proxy = gp4.getProxy(); proxy.login("lvyf", "123"); proxy.killBoss(); proxy.upgrade(); } }