java结构型设计模式——代理模式

来源:互联网 发布:python 矩阵处理 编辑:程序博客网 时间:2024/05/29 19:27

1、模式理解:代理模式很简单,就是一个对象代替另一个对象来执行相应的方法,比方说老师帮学生去考试,哈哈哈

2、运用场景:随便啦,爱咋用咋用

3、代码示例:

//先写一个接口,里面是学生和老师都有的方法public interface Work {void test();}
//再创建学生类,实现去考试的方法public class Student implements Work{@Overridepublic void test() {System.out.println("去考试");}}
//再创建老师类,替代学生,去实现去考试的方法public class Teacher implements Work{public Student student;@Overridepublic void test() {if (student==null) {student=new Student();}student.test();}}
//最后写个测试类测试一下public class Main {public static void main(String[] args) {Work teacher=new Teacher();teacher.test();}}