8种结构型模式 之1 PROXY 代理模式
代理模式也叫委托模式,给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。是一项基本的设计技巧。分为普通代理和强制代理。 另一个角度又分为静态代理和动态代理。
Subject接口
public interface Subject { void operation(String arg);}
RealSubject类
public class RealSubject implements Subject { @Override public void operation(String arg) { System.out.println("实际操作, 参数:" + arg); }}
ProxySubject类
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); }}
TestProxy 测试类:
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"); }}
测试结果:
1:普通代理:由代理生成真实角色,真是角色不能直接new出来

约定真实角色不能 直接 new ,必须通过代理类才能操作。
真实角色,构造函数中 有 代理类参数,做判断
public GamePlayer(IGamePlayer _gamePlayer,String _name) throws Exception{if(_gamePlayer == null ){throw new Exception("不能创建真是角色!");}else{this.name = _name;}}
代理类构造函数中 new 真实角色
public GamePlayerProxy(String name){try {gamePlayer = new GamePlayer(this,name);} catch (Exception e) {}}
测试类:
IGamePlayer proxy = new GamePlayerProxy("张三");proxy.login("zhangsan","password");
2:强制代理:由真是角色指定代理,不是指定的代理不能调方法

测试:
//定义个游戏的角色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");