强制代理
强制代理在设计模式中比较另类,一般的思维都是通过代理找到真实的角色,而强制代理则却是要“强制”,必须通过真实角色查找到代理角色,否则不能访问
不论是通过代理类还是直接new一个主题角色类,都不能访问,必须通过真实角色指定的代理类才能访问,也就是说由真实角色管理代理角色。这么说吧,高层模块new一个真实角色对象,但是返回的是代理角色。这好比,你去找明星帮忙,明星叫你去找经纪人
具体代码
//抽象主题类
public interface IGamePlayer {
//登录
public void login(String name, String password);
//杀怪
public void killBoss();
//升级
public void upgrade();
//寻找自己的代理
public IGamePlayer getProxy();
}
//真实主题类 被代理者,实际操作类
public class GamePlayer implements IGamePlayer{
private String name = "";
//指定的代理
private GamePlayProxy proxy = null;
public GamePlayer(String _name){
this.name = _name;
}
@Override
public void login(String name, String password) {
if (this.isProxy()){
System.out.println("登录名为:"+this.name);
}else {
System.out.println("请使用指定的代理类!");
}
}
@Override
public void killBoss() {
if (this.isProxy()){
System.out.println(this.name+"在杀怪");
}else {
System.out.println("请使用指定的代理类!");
}
}
@Override
public void upgrade() {
if (this.isProxy()){
System.out.println(this.name+"又升级了");
}else {
System.out.println("请使用指定的代理类!");
}
}
//指定代理类
@Override
public IGamePlayer getProxy() {
//在设计模式之禅123页
//this.proxy = new GamePlayProxy(this,name); 但是无法正确运行
this.proxy = new GamePlayProxy(this);
return this.proxy;
}
private boolean isProxy(){
if (this.proxy == null){
return false;
}else {
return true;
}
}
}
//代理类
public class GamePlayProxy implements IGamePlayer{
private IGamePlayer player = null;
public GamePlayProxy(IGamePlayer _player){
this.player = _player;
}
//代练登录
@Override
public void login(String name, String password) {
this.player.login(name,password);
}
//代练杀怪
@Override
public void killBoss() {
this.player.killBoss();
}
//代练
@Override
public void upgrade() {
this.player.upgrade();
}
//暂时没有代理类,返回自己
@Override
public IGamePlayer getProxy() {
return this;
}
}
//直接访问真实角色
public class main {
public static void main(String[] args) {
//定义一个玩家
IGamePlayer player= new GamePlayer("张三");
//玩家开始打游戏
System.out.println("----游戏玩家开始打游戏----");
player.login("张三","passwd");
player.killBoss();
player.upgrade();
}
}
结果图:
因为代码中要求了必须通过代理访问,不能直接和他进行交流
//直接访问代理类
public class main {
public static void main(String[] args) {
IGamePlayer player = new GamePlayer("张三");
//定义一个代练者
IGamePlayer proxy = new GamePlayProxy(player);
//代练开始打游戏
System.out.println("----代练开始打游戏----");
proxy.login("张三","passwd");
proxy.killBoss();
proxy.upgrade();
}
}
结果图:
不能访问的原因是代理类是由客户端自己new出来的,而不是真实角色生产的,就像是随便找了一个经纪人,明星当然不认
//强制代理的场景类
public class main {
public static void main(String[] args) {
//定义一个玩家
IGamePlayer player = new GamePlayer("张三");
IGamePlayer proxy = player.getProxy();
//指定代练开始打游戏
System.out.println("----指定代练开始打游戏----");
proxy.login("张三","passwd");
proxy.killBoss();
proxy.upgrade();
}
}
结果图:
强制代理的概念就是从真实角色查找代理角色,不允许直接访问真实角色,代理的管理由真实角色完成。
因为代理模式的实际操作是由真实角色操作的,而强制代理是限制了真实角色的操作,从而达到目的