前言:【模式總覽】——————————by xingoohtml
代理模式爲其餘的對象增長一個代理對象,進行訪問控制。從而避免直接訪問一個對象,形成效率或者安全性上的下降。安全
1 遠程代理,爲一個遠程對象,建立一個本地的代理對象。每次訪問,直接訪問本地代理對象便可。ide
2 虛代理,若是對象很大,直接訪問開銷很大,能夠爲他建立一個代理對象,只生成關鍵的信息便可。post
3 保護代理,爲某個對象增長一種保護機制,只有必定的權限才能經過這個代理,訪問後面的對象。spa
4 智能指針,有點像C++裏面的那個智能指針,爲指針進行計數和銷燬等操做。避免出現懸垂指針等現象。代理
Subject 類接口,定義代理類,實現類等的規範。指針
interface Subject{ public void request(); }
RealSubject 真正的對象code
class RealSubject implements Subject{ public void request() { System.out.println("ConcreteSubject request()"); } }
ProxySubject 代理類,能夠對真正的實現部分加上一種相似裝飾的效果。看!多像AOP!htm
class ProxySubject implements Subject{ private RealSubject subject; public void request() { preRequest(); if(subject == null){ subject = new RealSubject(); } subject.request(); postRequest(); } public void preRequest(){ System.out.println("ConcreteSubject preRequest()"); } public void postRequest(){ System.out.println("ConcreteSubject postRequest()"); } }
所有代碼對象
1 package com.xingoo.Proxy; 2 interface Subject{ 3 public void request(); 4 } 5 class ProxySubject implements Subject{ 6 private RealSubject subject; 7 8 public void request() { 9 preRequest(); 10 11 if(subject == null){ 12 subject = new RealSubject(); 13 } 14 subject.request(); 15 16 postRequest(); 17 } 18 19 public void preRequest(){ 20 System.out.println("ConcreteSubject preRequest()"); 21 } 22 23 public void postRequest(){ 24 System.out.println("ConcreteSubject postRequest()"); 25 } 26 } 27 class RealSubject implements Subject{ 28 public void request() { 29 System.out.println("ConcreteSubject request()"); 30 } 31 } 32 public class Client { 33 public static void main(String[] args) { 34 Subject subject = new ProxySubject(); 35 subject.request(); 36 } 37 }
運行結果
ConcreteSubject preRequest() ConcreteSubject request() ConcreteSubject postRequest()