1.普通代理#
1.1定义##
普通代理要求客户端只能访问代理角色,不能访问真实角色。
1.2实现##
1.2.1抽象角色类###
public interface IGamePlayer {
public void request();
}
1.2.2代理角色类###
public class GamePlayerProxy implements IGamePlayer{
private IGamePlayer gamePlayer = null;
public GamePlayerProxy(String _name) {
try {
gamePlayer = new GamePlayer(this, _name);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void request() {
this.before();
this.gamePlayer.request();
this.after();
}
private void before() {
//代理动作前处理
}
private void after() {
//代理动作后处理
}
}
1.2.3真实角色类###
public class GamePlayer implements IGamePlayer{
private String name = "";
public GamePlayer(IGamePlayer _gamePlayer, String _name) throws Exception{
if (_gamePlayer == null){
throw new Exception("无法生成真实角色!");
//此处添加一些创建的限制条件
}else{
this.name = _name;
}
}
@Override
public void request() {
System.out.println("处理具体的事物");
}
}
2.强制代理#
2.1定义##
强制代理要求必须通过真实角色查找到代理角色,否则不能访问。代理角色由真实角色自己管理,不需要知道代理角色,代理角色还可以有自己的代理。
2.2实现##
2.2.1抽象代理类###
public interface IGamePlayer {
public void request();
public IGamePlayer getProxy();
}
2.2.2具体代理类###
public class GamePlayerProxy implements IGamePlayer{
private IGamePlayer gamePlayer = null;
private String name = "";
public GamePlayerProxy(IGamePlayer _gamePlayer, String _name) {
this.gamePlayer = _gamePlayer;
this.name = _name;
}
@Override
public void request() {
this.before();
this.gamePlayer.request();
this.after();
}
//代理类还可以有自己的代理,此处没有所以返回自己
@Override
public IGamePlayer getProxy() {
return this;
}
private void before() {
//代理动作前处理
}
private void after() {
//代理动作后处理
}
}
2.2.3真实角色类###
public class GamePlayer implements IGamePlayer{
private String name = "";
private IGamePlayer proxy = null;
public GamePlayer(String _name) {
this.name = name;
}
@Override
public void request() {
if (this.proxy == null){
System.out.println("请获取代理角色!");
}else {
System.out.println("处理具体的事物");
}
}
@Override
public IGamePlayer getProxy() {
this.proxy = new GamePlayerProxy(this, name);
return proxy;
}
}
3.动态代理模式#
未完待续。。。
网友评论