Skip to content

Commit

Permalink
add bridge mode
Browse files Browse the repository at this point in the history
  • Loading branch information
senghoo committed Apr 10, 2016
1 parent 295fc9c commit d5f4abd
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 0 deletions.
7 changes: 7 additions & 0 deletions 22_bridge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# 桥接模式

桥接模式分离抽象部分和实现部分。使得两部分独立扩展。

桥接模式类似于策略模式,区别在于策略模式封装一系列算法使得算法可以互相替换。

策略模式使抽象部分和实现部分分离,可以独立变化。
59 changes: 59 additions & 0 deletions 22_bridge/bridge.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package bridge

import "fmt"

type AbstractMessage interface {
SendMessage(text, to string)
}

type MessageImplementer interface {
Send(text, to string)
}

type MessageSMS struct{}

func ViaSMS() MessageImplementer {
return &MessageSMS{}
}

func (*MessageSMS) Send(text, to string) {
fmt.Printf("send %s to %s via SMS", text, to)
}

type MessageEmail struct{}

func ViaEmail() MessageImplementer {
return &MessageEmail{}
}

func (*MessageEmail) Send(text, to string) {
fmt.Printf("send %s to %s via Email", text, to)
}

type CommonMessage struct {
method MessageImplementer
}

func NewCommonMessage(method MessageImplementer) *CommonMessage {
return &CommonMessage{
method: method,
}
}

func (m *CommonMessage) SendMessage(text, to string) {
m.method.Send(text, to)
}

type UrgencyMessage struct {
method MessageImplementer
}

func NewUrgencyMessage(method MessageImplementer) *UrgencyMessage {
return &UrgencyMessage{
method: method,
}
}

func (m *UrgencyMessage) SendMessage(text, to string) {
m.method.Send(fmt.Sprintf("[Urgency] %s", text), to)
}
29 changes: 29 additions & 0 deletions 22_bridge/bridge_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package bridge

func ExampleCommonSMS() {
m := NewCommonMessage(ViaSMS())
m.SendMessage("have a drink?", "bob")
// Output:
// send have a drink? to bob via SMS
}

func ExampleCommonEmail() {
m := NewCommonMessage(ViaEmail())
m.SendMessage("have a drink?", "bob")
// Output:
// send have a drink? to bob via Email
}

func ExampleUrgencySMS() {
m := NewUrgencyMessage(ViaSMS())
m.SendMessage("have a drink?", "bob")
// Output:
// send [Urgency] have a drink? to bob via SMS
}

func ExampleUrgencyEmail() {
m := NewUrgencyMessage(ViaEmail())
m.SendMessage("have a drink?", "bob")
// Output:
// send [Urgency] have a drink? to bob via Email
}

0 comments on commit d5f4abd

Please sign in to comment.