天天看點

學習Go語言之代理模式

一,關于代理模式:為其它對象提供一種代理以控制對這個對象的通路

學習Go語言之代理模式

二,網絡代理是一種常見的應用,那麼就舉一個簡單的示例來表示代理模式。

1 package main
 2 
 3 import "fmt"
 4 
 5 type NetWork interface {
 6     Conn()
 7     Close()
 8 }
 9 
10 // 聲明伺服器對象
11 type Server struct {
12     localIP string
13 }
14 
15 // 真實的網絡連接配接器,連接配接伺服器
16 type IpNetWork struct {
17     server *Server
18 }
19 
20 func (c *IpNetWork) Conn(serverIp string) {
21     c.server = &Server{localIP: serverIp}
22     fmt.Println(c.server.localIP + "已連接配接")
23 }
24 
25 func (c *IpNetWork) Close() {
26     fmt.Println(c.server.localIP + "已關閉連接配接")
27 }
28 
29 // 代理的網絡連接配接器,代理連接配接器
30 type ProxyNetWork struct {
31     Ip *IpNetWork
32 }
33 
34 func (c *ProxyNetWork) Conn(serverIp string) {
35     // 代理中實際使用的是真實的網絡連接配接器
36     c.Ip = &IpNetWork{}
37     c.Ip.Conn(serverIp)
38 }
39 
40 func (c *ProxyNetWork) Close() {
41     c.Ip.Close()
42 }
43 
44 func main() {
45     proxy := &ProxyNetWork{}
46     proxy.Conn("192.168.51.471")
47     proxy.Close()
48 }      
學習Go語言之代理模式

轉載于:https://www.cnblogs.com/shi2310/p/11418201.html