1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-25 14:36:06 +03:00
This commit is contained in:
cbping-pc 2017-11-08 11:00:57 +08:00
parent dc969fb3be
commit b9b87f9c41

View File

@ -4,47 +4,59 @@ Decouples an interface from its implementation so that the two can vary independ
## Implementation ## Implementation
```go ```go
type Info struct {
Sender // who or which way to send information. eg: QQ Wechat
MsgTag // the tag of msg. just like log level tag. eg: COMMON IMPORTANCE
}
func (i Info) Sending(to, msg string) {
msg = i.MsgTag(msg)
i.Sender.Send(to, msg)
}
// interface // interface
type Request interface {
HttpRequest() (*http.Request, error) type Sender interface {
Send(to, msg string)
} }
type Client struct { type MsgTag func(string) string
Client *http.Client
}
func (c *Client) Query(req Request) (resp *http.Response, err error) {
httpreq,_:=req.HttpRequest()
resp, err = c.Client.Do(httpreq)
return
}
// implementation // implementation
type BaiduRequest struct {
type QQSender struct {
} }
func (cdn *BaiduRequest) HttpRequest() (*http.Request, error) { func (QQSender) Send(to, msg string) {
return http.NewRequest("GET", "https://www.baidu.com", nil) fmt.Println("[QQ] send to " + to + " with message: " + msg)
} }
// implementation type WechatSender struct {
type Googleequest struct {
} }
func (cdn *Googleequest) HttpRequest() (*http.Request, error) { func (WechatSender) Send(to, msg string) {
return http.NewRequest("GET", "https://www.google.com/?hl=zh-cn&gws_rd=ssl", nil) fmt.Println("[Wechat] send to " + to + " with message: " + msg)
}
func ImportanceTag(msg string) string {
return "[IMPORTANCE] " + msg
}
func CommonTag(msg string) string {
return "[COMMON] " + msg
} }
``` ```
## Usage ## Usage
```go ```go
client := &Client{http.DefaultClient} info := &Info{MsgTag: ImportanceTag, Sender: QQSender{}}
info.Sending("cbping", "hello world")
baiduReq := &BaiduRequest{} info.Sender = WechatSender{}
fmt.Println(client.Query(baiduReq)) info.Sending("cbping", "hello world")
googleReq := &Googleequest{} info.MsgTag = CommonTag
fmt.Println(client.Query(googleReq)) info.Sending("cbping", "hello world")
``` ```