The Law of Demeter

更詳細的說法是“Law of Demeter for Functions/Methods” (LoD-F),簡單化Object之間的互動,讓多個Object不要互相相依。

定義:

The Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects:

  1. O itself
  2. M’s parameters
  3. Any objects created/instantiated within M
  4. O’s direct component objects
  5. A global variable, accessible by O, in the scope of M

範例:

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
/**
* A Law of Demeter example in Java.
* Created by Alvin Alexander, <a href="http://devdaily.com" title="http://devdaily.com">http://devdaily.com</a>.
* This is an adaptation of the source code example from the book
* The Pragmatic Programmer.
*/
public class LawOfDemeterInJava
{
private Topping cheeseTopping;

/**
* Good examples of following the Law of Demeter.
*/
public void goodExamples(Pizza pizza)
{
Foo foo = new Foo();

// (1) it's okay to call our own methods
doSomething();

// (2) it's okay to call methods on objects passed in to our method
int price = pizza.getPrice();

// (3) it's okay to call methods on any objects we create
cheeseTopping = new CheeseTopping();
float weight = cheeseTopping.getWeightUsed();

// (4) any directly held component objects
foo.doBar();
}

private void doSomething()
{
// do something here ...
}
}

參考資料: