接下来,我们引入一种应用场景。在工作中,我们会处于某个小组中。小组内的成员之间需要进行互相的沟通和交流。然后我们会有一个小组的工作群,我们在里面进行工作沟通和交流。这个小组群,其实就是我们的中介者。
package mediator
import (
"fmt"
)
type Member struct {
name string
}
func (m *Member) Name() string {
return m.name
}
func NewMember(name string) *Member {
return &Member{name: name}
}
func (m *Member) sendMessage(message string) {
ShowMessage(m, message)
}
// 定义一个函数直接调用来模式静态方法
func ShowMessage(member *Member, message string) {
fmt.Println("2019-05-28" + " [" + member.Name() + "] " + message)
}
package mediator
func ExampleMediator() {
peagsus := NewMember("Peagsus")
meteor := NewMember("Meteor")
ShowMessage(peagsus, "hello")
ShowMessage(meteor, "world")
//Output:
//2019-05-28 [Peagsus] hello
//2019-05-28 [Meteor] world
}
package tech.selinux.design.pattern.behavioral.mediator;
public class Member {
private String name;
public Member(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sendMessage(String message) {
WorkGroup.showMessage(this, message);
}
}
package tech.selinux.design.pattern.behavioral.mediator;
import java.util.Date;
public class WorkGroup {
public static void showMessage(Member member, String message) {
System.out.println(new Date().toString() + " [" + member.getName() + "] " + message);
}
}
package tech.selinux.design.pattern.behavioral.mediator;
public class Test {
public static void main(String[] args) {
Member peagsus = new Member("Pegasus");
Member meteor = new Member("Meteor");
peagsus.sendMessage("hello");
meteor.sendMessage("world");
}
}
补充另一个版本的Java/Scala Demo 以及源码解析