Java design pattern --- proxy mode (static proxy)

Not much nonsense, on the code:

We create a TeacherDao class to teach, and we need to create an agent teacher to teach.

Step 1: Create an interface first

public interface ITTeacherDao {
    public void teach();
}

Step 2: Create a teacher class for teaching

public class TeacherDao implements ITTeacherDao {
    @Override
    public void teach() {
        System.out.println("老师正在讲课");
    }
}

Step 3: Create a teacher to teach

//静态代理
public class TeacherDaoProxy implements ITTeacherDao {

    //目标对象 通过接口来聚合
    private ITTeacherDao target;

  //构造器
    public TeacherDaoProxy(ITTeacherDao target) {
        this.target = target;
    }

    @Override
    public void teach() {
        System.out.println("代理开始");
        target.teach();
        System.out.println("代理结束");
    }
}

The final test category and results:

public class TeacherTest001 {
    public static void main(String[] args) {
        //创建目标对象
        TeacherDao teacherDao = new TeacherDao();

        //创建代理对象,同时将被代理对象传递给代理对象
        TeacherDaoProxy teacherDaoProxy = new TeacherDaoProxy(teacherDao);

        //通过代理对象,调用被代理对象的方法
        teacherDaoProxy.teach();

    }
}


结果输出如下:
代理开始
老师正在讲课
代理结束

 

 

Guess you like

Origin blog.csdn.net/LB_Captain/article/details/113957654