天天看点

设计模式.迪米特法则

迪米特法则的简写是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,如需转载请自行联系原作者

继续阅读