在代理模式(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)); } }