Esempio n. 1
0
        public void EatFood()
        {
            // We've coupled ourselves to the Console implementation
            Console.WriteLine("I'm hungry, what do we have to eat? ");
            string food = Console.ReadLine();

            // We are newing classes here too!
            if (food == "orange")
            {
                var orange = new Orange();
                orange.Peel();
                orange.Eat();
            }
            else if (food == "steak")
            {
                var steak = new Steak();
                steak.Cook();
                steak.Eat();
            }
            //
            // Adding more types of foods means we need to add more conditional blocks and we need to know how to eat the pie too
            // This class can get complex and large fast if we don't invert the control of creating the food
            // We will also need to abstract how to eat food so we can invert the control of how to eat food to each food type
            //
            // Now what if we need a stomach class to know all of these types of food too?
            // For every type of food, we would need to now touch two classes as well as more code branches which grows the complexity further
            // Coding to abstractions (interfaces) and inverting control will make these classes easier to manage and evolve
            //
            else if (food == "apple pie")
            {
                var pie = new ApplePie();
                pie.Warm();
                pie.Eat();
            }
            else
            {
                Console.WriteLine("I don't know how to eat " + food);
                return;
            }

            Console.WriteLine("Thanks, that was good");
        }
Esempio n. 2
0
        public void FruitTest()
        {
            Banana banana = new Banana();
            Orange orange = new Orange(true);
            Grape  grape  = new Grape();
            Tomato tomato = new Tomato();

            orange.Peel();
            Mandarin      mandarin = new Mandarin(true);
            List <IFruit> basket   = new List <IFruit>();

            basket.Add(banana);
            basket.Add(grape);
            basket.Add(orange);
            basket.Add(mandarin);
            basket.Add(tomato);

            foreach (IFruit fruit in basket)
            {
                Console.WriteLine(fruit.Name != "grape" || fruit.Name != "tomato"
                                                ? fruit.Peel()
                                                : $"Can't peel {fruit.Name}");;
            }
        }