hooyantsing's Blog

P92 代理模式(2)-静态代理

字数统计: 278阅读时长: 1 min
2020/11/11

尚硅谷Java设计模式(图解+框架源码剖析)

静态代理

优点:在不修改目标对象的功能前提下,能通过代理对象对目标功能扩展。

缺点:因为代理对象需要与目标对象实现一样的接口,所以会有很多代理类。

一旦接口增加方法,目标对象与代理对象都要维护

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classDiagram
class ITeacherDao{
<<interface>>
+teach() void
}
class TeacherDao{
+teach() void
}
class TeacherDaoProxy{
+teach() void
}
class Client
ITeacherDao <|.. TeacherDao
ITeacherDao <|.. TeacherDaoProxy
TeacherDaoProxy o-- TeacherDao
TeacherDaoProxy <.. Client

案例 课堂

共同实现的接口

1
2
3
public interface ITeacherDao {
void teach();
}

被代理类

1
2
3
4
5
6
public class TeacherDao implements ITeacherDao {
@Override
public void teach() {
System.out.println("上课中");
}
}

代理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class TeacherDaoProxy implements ITeacherDao {
private TeacherDao teacherDao;

public TeacherDaoProxy(TeacherDao teacherDao) {
this.teacherDao = teacherDao;
}

@Override
public void teach() {
System.out.println("代理:准备上课");
teacherDao.teach();
System.out.println("代理:准备下课");
}
}

调用测试:

1
2
3
4
5
6
7
public class Client {
public static void main(String[] args) {
TeacherDao teacherDao = new TeacherDao();
ITeacherDao teacherDaoProxy = new TeacherDaoProxy(teacherDao);
teacherDaoProxy.teach();
}
}

执行结果:

1
2
3
代理:准备上课
上课中
代理:准备下课
CATALOG
  1. 1. 静态代理
  2. 2. 案例 课堂