1. 程式人生 > 其它 >Spring入門學習---05

Spring入門學習---05

Spring

代理模式

  代理模式分為兩大類:靜態代理 & 動態代理

  1、靜態代理

  我們以租車為例

角色分析:

  • 抽象角色
  • 真實角色
  • 代理角色
  • 客戶

程式碼實現:

  1.介面

package com.charles.dao;

// 租車
public interface RentCarMapper {

    public void rent();

}

  2.真實角色

public class HostRent implements RentCarMapper {
    @Override
    public void rent() {
        System.out.println(
"車主出租"); } }

  3.代理角色

public class RentCarProxy {

    private HostRent hostRent;

    public RentCarProxy(){}

    public RentCarProxy(HostRent hostRent){
        this.hostRent = hostRent;
    }

    public void rent(){
        hostRent.rent();
        visitCar();
        sign();
        receive();
    }

    
public void visitCar(){ System.out.println("中間商帶客戶看車"); } public void sign(){ System.out.println("簽署借租合同"); } public void receive(){ System.out.println("中間商賺差價"); } }

  4.客戶

public class Client {

    public static void main(String[] args) {
        HostRent hostRent 
= new HostRent(); RentCarProxy rentCarProxy = new RentCarProxy(hostRent); System.out.println("客戶租車"); rentCarProxy.rent(); } }

執行結果

  這樣的好處是:方便管理,分工明確

  缺點是:開發效率低

  這種思想正是AOP思想,而開發效率低的缺點,我們用動態代理來解決。

  2、動態代理

  動態代理顧名思義就是動態的代理類,我們這裡使用的是基於介面的代理----JDK 動態代理

  用到兩個類:Proxy & InvocationHandler

程式碼展示:

  代理類

public class RentCarProxy implements InvocationHandler {

    private HostRent hostRent;

    public void setHostRent(HostRent hostRent) {
        this.hostRent = hostRent;
    }

    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), hostRent.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        visitCar();
        sign();
        receive();
        Object invoke = method.invoke(hostRent, args);
        return invoke;
    }

    public void visitCar(){
        System.out.println("中間商帶客戶看車");
    }

    public void sign(){
        System.out.println("簽署借租合同");
    }

    public void receive(){
        System.out.println("中間商賺差價");
    }
}

  客戶

public class Client {

    public static void main(String[] args) {
        HostRent hostRent = new HostRent();
        RentCarProxy rentCarProxy = new RentCarProxy();
        // 通過呼叫程式處理角色來呼叫介面
        rentCarProxy.setHostRent(hostRent);
        // 動態生成的代理
        RentCarMapper proxy = (RentCarMapper) rentCarProxy.getProxy();
        proxy.rent();
    }
}

  這樣彌補了靜態代理的短缺