代理模式
一、什麼是代理模式
Proxy模式又叫做代理模式,是構造型的設計模式之一,它可以爲其他對象提供一種代理(Proxy)以控制對這個對象的訪問.
所謂代理,是指具有與代理元(被代理的對象)具有相同的接口的類,客戶端必須通過代理與被代理的目標類交互,而代理一般在交互的過程中(交互前後),進
行某些特別的處理。
二、代理模式的結構
三、代理模式的角色和職責
subject(抽象主題角色):
真實主題與代理主題的共同接口。
RealSubject(真實主題角色):
定義了代理角色所代表的真實對象。
Proxy(代理主題角色):
含有對真實主題角色的引用,代理角色通常在將客戶端調用傳遞給真是主題對象之前或者之後執行某些操作,而不是單純返回真實的對象。
四、動態代理
1. InvocationHandler接口
2. invoke方法
3. Proxy.newProxyInstance();
五、代碼靜態代理模式
package org.fbm.proxy;
//抽象的主題類
public interface Computer {
public void sellComputer();
}
package org.fbm.proxy;
//真實主題角色
public class ComputerCompany implements Computer {
public void sellComputer() {
System.out.println("我們賣的的是光禿禿的的電腦");
}
}
package org.fbm.proxy;
//代理類
public class ComputerProxy implements Computer {
private ComputerCompany computer;
public void sellComputer() {
if(computer==null){
computer=new ComputerCompany();
}
computer.sellComputer();
bestowMouse();
bestowKeyboard();
}
public void bestowMouse(){
System.out.println("我們經銷商還送鼠標");
}
public void bestowKeyboard(){
System.out.println("我們經銷商還送鍵盤");
}
}
package org.fbm.proxy;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
Computer computer=new ComputerProxy();
computer.sellComputer();
}
}
動態代理模式
package org.fbm.dynamicproxy;
//抽象類
public interface HumanLanguage {
public void say();
public void sell();
}
package org.fbm.dynamicproxy;
//實現角色
public class SayHumanLanguage implements HumanLanguage{
@Override
public void say() {
System.out.println("Can you call me 'father' ");
}
@Override
public void sell() {
System.out.println("Can you call me 'baby' ");
}
}
package org.fbm.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//代理角色
public class ProxyClass implements InvocationHandler {
public Object object;
public Object newProxyInstance(Object object) {
this.object = object;
return Proxy.newProxyInstance(object.getClass().getClassLoader(),
object.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object ret = null;
try {
//事前
System.out.println("fuck you");
//橫切面
ret = method.invoke(this.object, args);
//事後
System.out.println("巴嘎雅羅");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return ret;
}
}
package org.fbm.dynamicproxy;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ProxyClass proxy=new ProxyClass();
HumanLanguage hl=(HumanLanguage)proxy.newProxyInstance(new SayHumanLanguage());
hl.say();
hl.sell();
}
}