迪米特法则要求我们在设计系统时,应该尽量减少对象之间的交互,如果两个对象之间不必彼此直接通信,那么这两个对象就不应当发生任何直接的相互作用,如果其中的一个对象需要调用另一个对象的某一个方法的话,可以通过第三者转发这个调用。简言之,就是通过引入一个合理的第三者来降低现有对象之间的耦合度。
package demeter
type Member struct {
}
func NewMember() *Member {
return &Member{}
}
import (
"container/list"
"fmt"
)
type TeamLeader struct {
}
func NewTeamLeader() *TeamLeader {
return &TeamLeader{}
}
func (TeamLeader) checkNumberOfMember() {
l := list.New()
l.Init()
for i := 0; i < 20; i++ {
l.PushBack(NewMember())
}
fmt.Println(l.Len())
}
package demeter
type Boss struct {
}
func NewBoss() *Boss {
return &Boss{}
}
func (Boss) commandCheckNumber(leader *TeamLeader) {
}
package demeter
import "testing"
func Test(t *testing.T) {
boss := NewBoss()
boss.commandCheckNumber(NewTeamLeader())
}
package tech.selinux.design.principle.demeter;
public class Boss {
public void commandCheckNumber(TeamLeader teamLeader) {
teamLeader.checkNumberOfMember();
}
}
package tech.selinux.design.principle.demeter;
public class Member {}
package tech.selinux.design.principle.demeter;
import java.util.ArrayList;
import java.util.List;
public class TeamLeader {
public void checkNumberOfMember() {
List<Member> memberList = new ArrayList<Member>();
for (int i = 0; i < 20; i++) {
memberList.add(new Member());
}
System.out.println("组内成员数量" + memberList.size());
}
}
package tech.selinux.design.principle.demeter;
public class Test {
public static void main(String[] args) {
Boss boss = new Boss();
TeamLeader teamLeader = new TeamLeader();
boss.commandCheckNumber(teamLeader);
}
}
补充另一个版本的Java/Scala Demo 以及源码解析