代理模式

代理模式学习

目的

提供一个代理者进入其他对象,并且能够控制它

例如,购买火车票不一定要去火车站买,可以通过 12306 网站或者去火车票代售点买。又如找女朋友、找保姆、找工作等都可以通过找中介完成。

服务端代码

class Station implements BuyTheTicket{
 String buyTicket(User user){
    System.out.println("buy the ticket"):
  }
}
interface buyTheTicket{
 String  buyTicket(User user);
}

class User{
  private String username;
  public User(String username ){
    this.username = username;
  }  
}

class StationProxy implements  BuyTheTicket{
 private static final int NUM_USERS_ALLOWED = 3;

  private int numUsers;

  private final BuyTheTicket buyTheTicket;
  
  public StationProxy(BuyTheTicket buyTheTicket){
    this.buyTheTicket = buyTheTicket;
  }
  
 @Override
  public String buyTheTicket(User user){
    if(numWizards < NUM_USERS_ALLOWED){
      buyTheTicket.buyTheTicket(user);
      numUsers++;
    }else{
      Log.info("could not buy the ticket");
    }
  }
}

diagram-23069628274243756.png

参考文献:

代理模式

你可能感兴趣的:(代理模式)