8种结构型模式 之1 PROXY 代理模式
代理模式也叫委托模式,给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。是一项基本的设计技巧。分为普通代理和强制代理。 另一个角度又分为静态代理和动态代理。
Subject接口
public interface Subject { void operation(String arg);}
public class RealSubject implements Subject { @Override public void operation(String arg) { System.out.println("实际操作, 参数:" + arg); }}
public class ProxySubject implements Subject { private Subject beProxy; public ProxySubject(Subject beProxy) { this.beProxy = beProxy; } @Override public void operation(String arg) { System.out.println("代理操作, 参数:" + arg); beProxy.operation(arg); }}
public class TestProxy { public static void main(String[] args) { RealSubject realSubject = new RealSubject(); ProxySubject proxySubject = new ProxySubject(realSubject); System.out.println("------------Without Proxy ------------"); doSomething(realSubject); System.out.println("------------With Proxy ------------"); doSomething(proxySubject); } public static void doSomething(Subject subject){ subject.operation("flynewton"); }}
public GamePlayer(IGamePlayer _gamePlayer,String _name) throws Exception{if(_gamePlayer == null ){throw new Exception("不能创建真是角色!");}else{this.name = _name;}}
public GamePlayerProxy(String name){try {gamePlayer = new GamePlayer(this,name);} catch (Exception e) {}}
IGamePlayer proxy = new GamePlayerProxy("张三");proxy.login("zhangsan","password");
//定义个游戏的角色IGamePlayer player = new GamePlayer("张三");//获得指定的代理IGamePlayer proxy = player.getProxy();//开始打游戏,记下时间戳System.out.println("开始时间是:2009-8-25 10:45");proxy.login("zhangSan", "password");//开始杀怪proxy.killBoss();//升级proxy.upgrade();//记录结束游戏时间System.out.println("结束时间是:2009-8-26 03:40");