设计模式之 Proxy

为其他对象提供一种代理以控制对这个对象的访问。

例如:一个男孩找了个漂亮的女朋友, 他不想让女朋友和别的男孩子打电话, 于是他聘请了一个保镖,负责转接电话,如果是女孩给父亲或母亲打的,就转接过去,否则就拒绝。

package pattern;

interface Contact {
 
 void call(String str);
 
}

class Permission {

 public Boolean permit(String str){
  if (str.equals("mother")||str.equals("father"))
      return true;
  else return false;
 }
}

class Guard implements Contact {
 Contact contact;
 Permission perm;
 public Guard(Contact contact, Permission perm){
  this.contact = contact;
  this.perm = perm;
 }
 public void call(String str){
  if (perm.permit(str)){
   contact.call(str);
  }
  else {
   System.out.println("I am busy now.");
  }
 }
}

class ContactGirl implements Contact {
 
 public void call(String str){
  System.out.println("Hello "+str);
 }
 
}

public class Proxy {
 public static void main(String[] args){
  Contact girl = new ContactGirl();
  Permission perm = new Permission();
  Contact a = new Guard(girl, perm);
  a.call("a boy");
 }
}

通过Guard这个代理类,男孩就成功达到了限制女朋友和别的男孩通电话的目的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值