代理模式
Subject(抽象主题角色):真实主题与代理主题的共同接口。
RealSubject(真实主题角色):定义了代理角色所代表的真实对象。
Proxy(代理主题角色):含有对真实主题角色的引用,代理角色通常在将客户端调用传递给真是主题对象之前或者之后执行某些操作,而不是单纯返回真实的对象。
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| package main
import "fmt"
type Goods struct { Kind string Fact bool }
type Shopping interface { Buy(goods *Goods) }
type KoreaShopping struct {}
func (ks *KoreaShopping) Buy(goods *Goods) { fmt.Println("去韩国进行了购物, 买了 ", goods.Kind) }
type AmericanShopping struct {}
func (as *AmericanShopping) Buy(goods *Goods) { fmt.Println("去美国进行了购物, 买了 ", goods.Kind) }
type AfrikaShopping struct {}
func (as *AfrikaShopping) Buy(goods *Goods) { fmt.Println("去非洲进行了购物, 买了 ", goods.Kind) }
type OverseasProxy struct { shopping Shopping }
func (op *OverseasProxy) Buy(goods *Goods) { if (op.distinguish(goods) == true) { op.shopping.Buy(goods) op.check(goods) } }
func NewProxy(shopping Shopping) Shopping { return &OverseasProxy{shopping} }
func (op *OverseasProxy) distinguish(goods *Goods) bool { fmt.Println("对[", goods.Kind,"]进行了辨别真伪.") if (goods.Fact == false) { fmt.Println("发现假货",goods.Kind,", 不应该购买。") } return goods.Fact }
func (op *OverseasProxy) check(goods *Goods) { fmt.Println("对[",goods.Kind,"] 进行了海关检查, 成功的带回祖国") }
func main() { g1 := Goods{ Kind: "韩国面膜", Fact: true, }
g2 := Goods{ Kind: "CET4证书", Fact: false, }
var shopping Shopping shopping = new(KoreaShopping)
if g1.Fact == true { fmt.Println("对[", g1.Kind,"]进行了辨别真伪.") shopping.Buy(&g1) fmt.Println("对[",g1.Kind,"] 进行了海关检查, 成功的带回祖国") }
fmt.Println("---------------以下是 使用 代理模式-------") var overseasProxy Shopping overseasProxy = NewProxy(shopping) overseasProxy.Buy(&g1) overseasProxy.Buy(&g2) }
|