迪米特法则例子

 

迪米特法则(Law of Demeter)又叫作最少知识原则(Least Knowledge Principle 简写LKP),就是说一个对象应当对其他对象有尽可能少的了解,不和陌生人说话。英文简写为: LoD.

using System;

namespace ConsoleApplication4
{
    public class Assistant
    {
        public bool buySomeVet(string vet)
        {
            Console.WriteLine("购买一些蔬菜:" + vet);
            return true;
        }
        public bool buySomeRice(string rice)
        {
            Console.WriteLine("购买一些米:" + rice);
            return true;
        }
        public bool buySomeMeat(string meat)
        {
            Console.WriteLine("购买一些猪肉:" + meat);
            return true;
        }
    }

    public class Chef
    {
        public void getMaterial(Assistant assitant)
        {
            if (assitant.buySomeVet("菠菜"))
            {
                Console.WriteLine("买完菠菜接着买:米");
                if (assitant.buySomeRice("东北大米"))
                {
                    Console.WriteLine("买完东北大米接着买:猪肉");
                }
                if (assitant.buySomeMeat("五花肉"))
                {
                    Console.WriteLine("购买了全部所需食材,棒!");
                }
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Chef chef = new Chef();
            chef.getMaterial(new Assistant());
        }
    }
}

 

 

 

using System;

namespace ConsoleApplication4
{
    public class Assistant
    {
        public bool buySomeVet(string vet)//购买蔬菜
        {
            Console.WriteLine("购买一些蔬菜:"+ vet );
            return true;
        }
        public bool buySomeRice(string rice)//购买大米
        {
            Console.WriteLine("购买一些米:" + rice);
            return true;
        }
        public bool buySomeMeat(string meat)//购买猪肉
        {
            Console.WriteLine("购买一些猪肉:"+ meat);
            return true;
        }

        public void buyAllMaterial(string vet, string rice, string meat)//助手采购食材
        {
            if (this.buySomeVet("菠菜"))
            {
                Console.WriteLine("买完菠菜接着买:米");
                if (this.buySomeRice("东北大米"))
                {
                    Console.WriteLine("买完东北大米接着买:猪肉");
                }
                if (this.buySomeMeat("五花肉"))
                {
                    Console.WriteLine("厨师不需要管我是什么顺序买的所需食材,我自行买完了就好!");
                }
            }
        }
    }


    public class Chef
    {//厨师只将所需购买食材告诉助手Assistant,Assistant怎么去买不是厨师关心的事情
        public void getMaterial(Assistant assitant,string vet,string rice,string meat)
        {
            assitant.buyAllMaterial(vet,rice,meat);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Chef chef = new Chef();
            chef.getMaterial(new Assistant(), "菠菜", "东北大米", "五花肉");
        }
    }
}

 

 

posted @ 2019-10-15 11:12  liyitongxue  阅读(730)  评论(0)    收藏  举报