在代理模式(Proxy Pattern)中,一个类表明另外一个类的功能。这种类型的设计模式属于结构型模式。设计模式
在代理模式中,咱们建立具备现有对象的对象,以便向外界提供功能接口。安全
意图
为其余对象提供一种代理以控制对这个对象的访问。less
主要解决
在直接访问对象时带来的问题。
好比说:要访问的对象在远程的机器上。在面向对象系统中,有些对象因为某些缘由(好比对象建立开销很大,或者某些操做须要安全控制,或者须要进程外的访问),直接访问会给使用者或者系统结构带来不少麻烦,咱们能够在访问此对象时加上一个对此对象的访问层。ide
什么时候使用
想在访问一个类时作一些控制。设计
如何解决
增长中间层。代理
关键代码
实现与被代理类组合。code
原有售票服务,如今代理售票点一样提供售票服务,没必要跑到机场、长途大巴车站购买票。
代理售票点,只是简单作了记帐。对象
适配器模式有以下三个角色
Target:目标接口SellTicketsService
Product:目标实现产品类SellTicketsServiceImpl
Proxy:代理实现类ProxySellTicketsServiceImpl
接口
step 1:目标接口进程
public interface SellTicketsService { String sell(String type, BigDecimal amount); }
public class SellTicketsServiceImpl implements SellTicketsService { private Map<String, Integer> ticketCollection = new ConcurrentHashMap<String, Integer>() {{ put("air", 15); put("bus", 35); }}; @Override public String sell(String type, BigDecimal amount) { if (amount.doubleValue() < 0.0D) { throw new IllegalArgumentException("amount can not less than zero."); } Integer count = ticketCollection.get(type); if (count == null || count < 0) { throw new IllegalStateException("ticket collection is empty"); } count = ticketCollection.computeIfPresent(type, (k,v) -> v - 1); if (count == 0){ ticketCollection.remove(type); } return "ok"; } }
public class ProxySellTicketsServiceImpl implements SellTicketsService { private static final Logger logger = LoggerFactory.getLogger(ProxySellTicketsServiceImpl.class); private SellTicketsService service = new SellTicketsServiceImpl(); @Override public String sell(String type, BigDecimal amount) { logger.info("sell type:{} amount:{}",type,amount); return service.sell(type,amount); } public static void main(String[] args) { System.out.println(new ProxySellTicketsServiceImpl().sell("bus",BigDecimal.ONE)); } }