迪米特法則的簡寫是LOD,Law of Demeter,又叫最少知識原則(Least Knowledge Principle, LKP)
用一句話來解釋就是“一個對象應當對其他對象有盡可能少的了解。”
這個法則可以通過一個例子來描述,現在需要向計算機使用者輸出1+1的結果,那麼我們可以分解這個操作到兩個類中,一個類用來輸出,一個類用來計算。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DemeterLaw
{
class Program
{
static void Main(string[] args)
{
ShowResult.Show(Compute.Add(1,1).ToString());
Console.Read();
}
}
class ShowResult
public static void Show(string str)
Console.WriteLine(str);
class Compute
public static int Add(int a, int b)
return a + b;
}
兩個對象隻需要知道對方能夠做什麼即可,不用關心怎麼實作。看起來這個法則比較簡單,實際應用中有很多可以分解的地方。
本文轉自wengyuli 51CTO部落格,原文連結:http://blog.51cto.com/wengyuli/586769,如需轉載請自行聯系原作者