spring–动态代理(Spring — dynamic proxy)

动态代理自己理解:

    1.定义了一个公共的接口

    2.一个类实现了这个类,并实现其中的方法

    3.代理类,实现接口,将上面的类对象拿过来,并且在第一个类方法的基础上,拓展了自己的方法

    4.创建第一个类对象,创建代理类对象,将第一个类的对象给代理类

    5.代理类调用自己的方法

接口:定义一个公共的方法

package com.kuang.demo1;

/**
 * @author Administrator
 * @description: TODO
 * @date 2021/11/25 17:21
 */

public interface Rent {
    //接口;抽象;租房
    public void rent();
}

真实角色(第一个类)

package com.kuang.demo1;

/**
 * @author Administrator
 * @description: TODO
 * @date 2021/11/25 17:23
 */
//房东
public class Host implements Rent {

    public void rent() {
        System.out.println("出租房屋");
    }
}

代理类

package com.kuang.demo1;
public class Proxy implements Rent {
    private Host host;

    public Proxy(){};
    //将房东对象拿过来使用
    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        host.rent();
        look();
        write();
        money();
    }

    public void look() {
        System.out.println("看房");

    }
    public void write() {
        System.out.println("签合同");

    }
    public void money() {
        System.out.println("收费");

    }

}

使用者

package com.kuang.demo1;
public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        //去找中介租房
        proxy.rent();
    }
}
————————

Dynamic agents understand:

1. A public interface is defined

2. A class implements this class and implements its methods

3. The proxy class implements the interface, takes the above class object, and expands its own method based on the first class method

4. Create the first class object, create the proxy class object, and give the object of the first class to the proxy class

5. The proxy class calls its own methods

Interface: define a common method

package com.kuang.demo1;

/**
 * @author Administrator
 * @description: TODO
 * @date 2021/11/25 17:21
 */

public interface Rent {
    //接口;抽象;租房
    public void rent();
}

Real character (first class)

package com.kuang.demo1;

/**
 * @author Administrator
 * @description: TODO
 * @date 2021/11/25 17:23
 */
//房东
public class Host implements Rent {

    public void rent() {
        System.out.println("出租房屋");
    }
}

proxy class

package com.kuang.demo1;
public class Proxy implements Rent {
    private Host host;

    public Proxy(){};
    //将房东对象拿过来使用
    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        host.rent();
        look();
        write();
        money();
    }

    public void look() {
        System.out.println("看房");

    }
    public void write() {
        System.out.println("签合同");

    }
    public void money() {
        System.out.println("收费");

    }

}

User

package com.kuang.demo1;
public class Client {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        //去找中介租房
        proxy.rent();
    }
}