【设计模式无难事】——代理

【设计模式无难事】——代理
这里写图片描述
一、意图
为其他对象提供一种代理以控制对这个对象的访问。

二、例子
需求场景
法师进入魔法塔

分析&实作
代理模式实现
1,魔法塔接口
WizardTower.java

/**
 * WizardTower interface
 */
public interface WizardTower {

  void enter(Wizard wizard);
}

2,实现接口
IvoryTower.java

/**
 * 
 * The object to be proxyed.
 * 
 */
public class IvoryTower implements WizardTower {

  private static final Logger LOGGER = LoggerFactory.getLogger(IvoryTower.class);

  public void enter(Wizard wizard) {
    LOGGER.info("{} enters the tower.", wizard);
  }

}

3,定义一个法师类
Wizard.java

/**
 * 
 * Wizard
 *
 */
public class Wizard {

  private final String name;

  public Wizard(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return name;
  }

}

4,做一个魔法塔代理类
WizardTowerProxy.java

/**
 * 
 * The proxy controlling access to the {@link IvoryTower}.
 * 
 */
public class WizardTowerProxy implements WizardTower {

  private static final Logger LOGGER = LoggerFactory.getLogger(WizardTowerProxy.class);

  private static final int NUM_WIZARDS_ALLOWED = 3;

  private int numWizards;

  private final WizardTower tower;

  public WizardTowerProxy(WizardTower tower) {
    this.tower = tower;
  }

  @Override
  public void enter(Wizard wizard) {
    if (numWizards < NUM_WIZARDS_ALLOWED) {
      tower.enter(wizard);
      numWizards++;
    } else {
      LOGGER.info("{} is not allowed to enter!", wizard);
    }
  }
}

5,运行

public static void main(String[] args) {
    WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower());
    proxy.enter(new Wizard("Red wizard"));
    proxy.enter(new Wizard("White wizard"));
    proxy.enter(new Wizard("Black wizard"));
    proxy.enter(new Wizard("Green wizard"));
    proxy.enter(new Wizard("Brown wizard"));
  }
}

6,输出

16:46:42.993 [main] INFO com.iluwatar.proxy.IvoryTower - Red wizard enters the tower.
16:46:42.998 [main] INFO com.iluwatar.proxy.IvoryTower - White wizard enters the tower.
16:46:42.998 [main] INFO com.iluwatar.proxy.IvoryTower - Black wizard enters the tower.
16:46:42.998 [main] INFO com.iluwatar.proxy.WizardTowerProxy - Green wizard is not allowed to enter!
16:46:42.998 [main] INFO com.iluwatar.proxy.WizardTowerProxy - Brown wizard is not allowed to enter!

三、思考
1,代理类在使用者真实服务对象之间增加了一个“层”,通过非侵入式改造对象,为真实服务对象增加更多的控制功能。

2,代理侧重点在控制访问。

Tips:一个类,它提供了对一个接口的访问控制,是代理模式的特征

四、代理模式在android源码中的例子

附:
本文源代码在这里
有任何问题,欢迎留言或Email我 zzy_2002@126.com
转载请注明出处:http://blog.csdn.net/zzy_801011/article/details/79035321
谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值