设计模式-深入理解各种代理模式(2)通俗代码版

3》多代理模式:提高或增强代理的其他业务,如:拦截、过滤等

public interface IGamePlayer {


//登录游戏
public void login(String user,String password);

//杀怪,这是网络游戏的主要特色
public void killBoss();

//升级
public void upgrade();
}

---

public interface IProxy {
//计算费用
public void count();
}

---

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,IProxy {
private IGamePlayer gamePlayer = null;

//通过构造函数传递要对谁进行代练
public GamePlayerProxy(IGamePlayer _gamePlayer){

this.gamePlayer = _gamePlayer;
}

//代练杀怪
public void killBoss() {
this.gamePlayer.killBoss();
}


//代练登录
public void login(String user, String password) {
this.gamePlayer.login(user, password);


}


//代练升级
public void upgrade() {
this.gamePlayer.upgrade();
this.count();
}

//计算费用
public void count(){
System.out.println("升级总费用是:150元");
}

}


---

public class Client {
public static void main(String[] args) {
//定义一个痴迷的玩家
IGamePlayer player = new GamePlayer("张三");

//然后再定义一个代练者
IGamePlayer proxy = new GamePlayerProxy(player);

//开始打游戏,记下时间戳
System.out.println("开始时间是:2009-8-25 10:45");
proxy.login("zhangSan", "password");
//开始杀怪
proxy.killBoss();
//升级
proxy.upgrade();
//记录结束游戏时间
System.out.println("结束时间是:2009-8-26 03:40");
}
}


4》虚拟代理:在每个方法前判断下真实主题(被代理对象)是否初始化,没有初始化 new  真实被代理对象即可

 比如:

public class Client {
public static void main(String[] args) {
//定义一个痴迷的玩家
IGamePlayer player = null;

//然后再定义一个代练者
IGamePlayer proxy = new GamePlayerProxy(player);  // 必须在 GamePlayerProxy 构造方法类初始化player

//开始打游戏,记下时间戳
System.out.println("开始时间是:2009-8-25 10:45");
proxy.login("zhangSan", "password");
//开始杀怪
proxy.killBoss();
//升级
proxy.upgrade();
//记录结束游戏时间
System.out.println("结束时间是:2009-8-26 03:40");
}
}

----------------------------------

//通过构造函数传递要对谁进行代练
public GamePlayerProxy(IGamePlayer _gamePlayer){

                if(_gamePlayer== null){

                   _gamePlayer=new GamePlayer("张三");

                 }

this.gamePlayer = _gamePlayer;
}



posted @ 2014-09-21 22:12  172257861  阅读(113)  评论(0编辑  收藏  举报