Striveonger

vuePress-theme-reco Mr.Lee    2015 - 2025
Striveonger Striveonger
主页
分类
  • 笔记
  • 文章
  • 工具
标签
时间轴
简历
author-avatar

Mr.Lee

269

Article

137

Tag

主页
分类
  • 笔记
  • 文章
  • 工具
标签
时间轴
简历

设计模式(八) -- 代理模式

vuePress-theme-reco Mr.Lee    2015 - 2025

设计模式(八) -- 代理模式

Mr.Lee 2021-04-19 20:00:23 设计模式

设计模式之代理模式

# 定义:

代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。

在某些情况下,一个客户类不想或者不能直接引用一个委托对象,而代理类对象可以在客户类和委托对象之间起到中介的作用,其特征是代理类和委托类实现相同的接口。

# 开闭原则,增加功能:

代理类除了是客户类和委托类的中介之外,我们还可以通过给代理类增加额外的功能来扩展委托类的功能,这样做我们只需要修改代理类而不需要再修改委托类,符合代码设计的开闭原则。代理类主要负责为委托类预处理消息、过滤消息、把消息转发给委托类,以及事后对返回结果的处理等。代理类本身并不真正实现服务,而是同过调用委托类的相关方法,来提供特定的服务。真正的业务功能还是由委托类来实现,但是可以在业务功能执行的前后加入一些公共的服务。例如我们想给项目加入缓存、日志这些功能,我们就可以使用代理类来完成,而没必要打开已经封装好的委托类。

# 代理模式分类

# 静态代理

image-20210419212423894

package com.striveonger.proxy.behavior;

/**
 * @description: 买车
 * @author Mr.Lee
 * @date 2021-04-19 20:46
 */
public interface BuyCar {
    void buy();
}
1
2
3
4
5
6
7
8
9
10
package com.striveonger.proxy.behavior;

/**
 * @description: 买二手车
 * @author Mr.Lee
 * @date 2021-04-19 20:48
 */
public class BuyOldCar implements BuyCar {

    @Override
    public void buy() {
        System.out.println("购得七手的奥拓");
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.striveonger.proxy.behavior.static_proxy;

/**
 * @description: 代理类接口
 * @author Mr.Lee
 * @date 2021-04-19 20:57
 */
public interface ProxySurround {

    void before();

    void after();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.striveonger.proxy.behavior.static_proxy;

import com.striveonger.proxy.behavior.BuyCar;

/**
 * @description: 静态代理
 * @author Mr.Lee
 * @date 2020-04-19 20:52
 */
public class ProxyBuyOldCar implements BuyCar, ProxySurround {

    private BuyCar proxy;

    public ProxyBuyOldCar(BuyCar proxy) {
        this.proxy = proxy;
    }

    @Override
    public void buy() {
        before();
        proxy.buy();
        after();
    }

    @Override
    public void before() {
        System.out.println("质检");
    }

    @Override
    public void after() {
        System.out.println("过户");
    }
}

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
27
28
29
30
31
32
33
34
35
package com.striveonger.proxy.behavior.static_proxy;

import com.striveonger.proxy.behavior.BuyCar;
import com.striveonger.proxy.behavior.BuyOldCar;
import junit.framework.TestCase;

/**
 * @description: 静态代理测试类
 * @author Mr.Lee
 * @date 2021-04-19 21:05
 */
public class BuyOldCarTest extends TestCase {

    public void testBuyOldCar() {
        System.out.println("---自己买二手车---");
        BuyCar buyCar = new BuyOldCar();
        buyCar.buy();
        System.out.println();
        System.out.println("---通过代理买二手车---");
        ProxyBuyOldCar proxy = new ProxyBuyOldCar(buyCar);
        proxy.buy();
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

执行结果:

---自己买二手车---
购得七手的奥拓

---通过代理买二手车---
质检
购得七手的奥拓
过户
1
2
3
4
5
6
7

# 动态代理