Posts 【结构型】代理模式详解
Post
Cancel

【结构型】代理模式详解

【结构型】代理模式

定义

1
2
3
4
5
6
定义:为其他对象提供一种代理以控制对这个对象的访问。

代理模式几个角色:
    1.主题接口:提取真正使用类与代理类的公共方法
    2.真正主题:真正处理请求的类
    3.代理类:真正主题的代理类

UML图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
                 _ _ _ _ _ _ _
                |             |
                | Interface   |
                |_ _ _ _ _ _ _|
                      ↑
                      |
        ┌----------------------------┐
  _ _ _ |_ _ _ _              _ _ _ _|_ _ _
 |              |            |             |
 |   Proxy      |-----------→| RealSubject |
 |_  _ _ _ _ _ _|            |_ _ _ _ _ _ _|
        ↑
        |
  _ _ _ _ _ __ _
 |              |
 |   Client     |
 |_  _ _ _ _ _ _|

代码

1
2
3
4
public interface Network{

    public  void innerNet();
}

1
2
3
4
5
6
7
8
public class BeijingNetwork implements Network{

    @override
    public void innerNet(){

        System.out.println("This is inner net");
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public ProxyNetWork implements Network{

    private BeijingNetwork bjNetwork;


public ProxyNetWork(){

        this.bjNetwork = new BeijingNetwork();
    }


    @override
    public void innerNet(){

        bjNetwork.innerNet();
    }

}


1
2
3
4
5
6
7
8
9
10
11
12
public class Client{


    public static void main(String[] args){

        ProxyNetWork proxy = new ProxyNetWork();

        proxy.innerNet();

    }

}

应用


This post is licensed under CC BY 4.0 by the author.

【结构型】装饰器模式详解

【结构型】外观模式详解