1
2 1------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
2
静态代理
java的设计模式的代理模式,就是静态代理
写在前面的话,静态代理的优点和缺点
优点:可以在不改变一个类的方法下,对这个类的方法进行增强
缺点:静态代理需要创建物理文件,在想实现多个静态代理的操作,就需要好多的物理文件,不太优良
实现案例:
Subject接口:抽象主题的接口,有一个方法
1
2
3
4
5
6
7
8
9 1package cn.dawn.day08proxy;
2
3/**
4 * Created by Dawn on 2018/3/6.
5 */
6public interface Subject {
7 public void request();
8}
9
RealSubject类:真实主题的类,实现上面的Subject接口,实现他的方法
1
2
3
4
5
6
7
8
9
10
11
12 1package cn.dawn.day08proxy;
2
3
4/**
5 * Created by Dawn on 2018/3/6.
6 */
7public class RealSubject implements Subject {
8 public void request() {
9 System.out.println("request本身——————————————————————————————-");
10 }
11}
12
ProxySubject类:代理主题的类,同样实现Subject接口,里面有个Subject的接口的实例对象,他的get/set方法,还有新的方法,对真实主题进行静态的增强
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 1package cn.dawn.day08proxy;
2
3/**
4 * Created by Dawn on 2018/3/6.
5 */
6public class ProxySubject implements Subject {
7 Subject subject;
8 public void request() {
9 System.out.println("before");
10 subject.request();
11 System.out.println("after");
12
13 }
14
15 public Subject getSubject() {
16 return subject;
17 }
18
19 public void setSubject(Subject subject) {
20 this.subject = subject;
21 }
22}
23
单测方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 1package cn.dawn.day08proxy;
2
3
4import org.junit.Test;
5import org.springframework.context.ApplicationContext;
6import org.springframework.context.support.ClassPathXmlApplicationContext;
7
8/**
9 * Created by Dawn on 2018/3/3.
10 */
11public class test20180306 {
12
13
14 @Test
15 /*di注解注入*/
16 public void t01(){
17 Subject realSubject=new RealSubject();
18
19 ProxySubject proxySubject=new ProxySubject();
20 proxySubject.setSubject(realSubject);
21 proxySubject.request();
22
23 //realSubject.request();
24 }
25}
26