Esempio n. 1
0
        static void Main(string[] args)
        {
            Wolf           wolf1   = new Wolf(name: "Grey");
            Fox            fox1    = new Fox(name: "Red", TimeSleeping: 8, WhatEat: "meat");
            Fox            fox2    = new Fox(name: "Masya", TimeSleeping: 7, speed: 50, WhatEat: "fish");
            List <Animals> animals = new List <Animals>
            {
                fox1, wolf1, fox2
            };

            foreach (var item in animals)
            {
                Console.WriteLine("\n\n-----------Animal--------------");
                Console.WriteLine(item);
            }

            fox1.Walk();
            fox2.Walk();
            wolf1.Walk();
            fox1.Sleep();
            fox2.Sleep();
            wolf1.Sleep();



            ZooWorker worker1 = new ZooWorker("Ivan");
            ZooWorker worker2 = new ZooWorker("Sasha");

            List <ZooWorker> workers = new List <ZooWorker>
            {
                worker1, worker2
            };

            foreach (var item in workers)
            {
                Console.WriteLine("\n\n-----------Zoo worker--------------");
                Console.WriteLine(item);
            }


            worker1.Worker_Must_Doing(fox1);
            worker1.Worker_Must_Doing(wolf1);
            worker2.Worker_Must_Doing(fox2);

            VideoCamera camera1 = new VideoCamera();
            VideoCamera camera2 = new VideoCamera();

            camera1.Watch(worker1, wolf1);
            camera2.Watch(worker2, fox2);
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            List <Guest>    guests            = new List <Guest>();
            List <Thread>   threads           = new List <Thread>();
            AnimalContainer elephantContainer = new AnimalContainer("Elephants");
            List <Elephant> elephants         = new List <Elephant>();
            float           timeWarp          = 0.0001f;

            for (int i = 0; i < 6; i++)
            {
                elephants.Add(new Elephant());
                elephantContainer.PlaceAnimal(elephants[i]);
                Elephant elephant = elephants[i];
                Thread   thread   = new Thread(() => elephant.Exist(timeWarp));
                threads.Add(thread);
            }
            AnimalContainer foxContainer = new AnimalContainer("Fox");
            List <Fox>      foxes        = new List <Fox>();

            for (int i = 0; i < 6; i++)
            {
                foxes.Add(new Fox());
                foxContainer.PlaceAnimal(foxes[i]);
                Fox    fox    = foxes[i];
                Thread thread = new Thread(() => fox.Exist(timeWarp));
                threads.Add(thread);
            }
            List <AnimalContainer> animalContainers = new List <AnimalContainer>
            {
                elephantContainer,
                foxContainer,
            };
            ZooPark zoo = new ZooPark(animalContainers);

            for (int i = 0; i < 300; i++)
            {
                Guest guest = new Guest();
                guests.Add(guest);
                Thread thread = new Thread(() => guest.GoToPark(zoo));
                threads.Add(thread);
            }
            EventWaitHandle[] handles = new EventWaitHandle[animalContainers.Count];
            for (int i = 0; i < animalContainers.Count; i++)
            {
                handles[i] = animalContainers[i].hasShit;
            }
            List <Worker> workers = new List <Worker>();

            for (int i = 0; i < 2; i++)
            {
                Worker worker = new Worker(zoo);
                Thread thread = new Thread(() => worker.Work(timeWarp));
                threads.Add(thread);
            }
            for (int i = 0; i < threads.Count; i++)
            {
                threads[i].Start();
            }
            ConsoleColor originalColor = Console.BackgroundColor;

            while (true)
            {
                int maxLenth = 0;
                foreach (AnimalContainer container in animalContainers)
                {
                    // Find max length of all containers
                    maxLenth = maxLenth < container.Name.Length ? container.Name.Length : maxLenth;
                }
                Console.WriteLine();
                for (int i = 0; i < animalContainers.Count; i++)
                {
                    Console.SetCursorPosition(0, i);
                    Console.Write(animalContainers[i].Name);
                    Console.SetCursorPosition(maxLenth + 1, i);
                    float poopAmount = animalContainers[i].Shits.Count / 500.0f;
                    poopAmount = poopAmount > 1 ? 1 : poopAmount;
                    Console.BackgroundColor = ConsoleColor.DarkRed;
                    // Calculate amount of space left
                    float ratio = (Console.BufferWidth - maxLenth - 2) * poopAmount;
                    for (int j = 0; j < (int)(ratio); j++)
                    {
                        Console.Write(' ');
                    }
                    Console.BackgroundColor = originalColor;
                }
                Console.WriteLine();
                int index = WaitHandle.WaitAny(handles);
                handles[index].Reset();
                Console.WriteLine("Container " + animalContainers[index].Name + " has shit");
            }
        }
Esempio n. 3
0
        private static void TestPolymorphism()
        {
            // Променлива от тип ICarnivore. Може да сочи към обект, който наследява интерфейс ICarnivore.
            // Чрез нея могат да бъдат достъпени методите описани в този интерфейс
            // както и методите описани в Object, защото всичко така или иначе наследява Object
            ICarnivore carnivore = CreateCarnivore();

            carnivore.EatMeat();
            carnivore.ToString();

            //Но чрез нея не могат да бъдат извикани методите на обект Fox, тък като тя (променливата) не е от тип Fox.
            //carnovore.StealTheCheese()


            //Променлива от тип AbstractAnimal. Може да сочи към обект, който наследява обект AbstractAnimal.
            //Чрез нея могат да бъдат достъпени методите описани в AbstractAnimal,
            //както и методите описани в Object, защото всичко така или иначе наследява Object
            //Но пак както преди не може да бъде използвана за извикване на методите на FOX
            AbstractAnimal anyAnimal = CreateAbstractAnimal();

            //Променлива от тип Object, може да сочи към всичко, защото всичко всъщност наследява Object, директно или не.
            //Но може да бъде използвана за извикване само на методи дефинирани в Object
            Object obj = CreateObject();

            obj.GetHashCode();

            // променлива от тип IHerbivore. Може да сочи към обект наследяващ IHerbivore - Elephant, Rabbit или Fox,
            // но не може да сме 100% сигурни към кое от тях без да сме проверили
            IHerbivore herbivore = CreateHerbivore();

            // може да проверим дали случайно не сочи към Rabbit
            if (herbivore is Rabbit)
            {
                // по случайност сочи към обект който всъщност е Rabbit
                Rabbit r;              // създаваме променлива от тип Заек - тя може да сочи само към обект от тип Заек.
                r = (Rabbit)herbivore; // тъй като вече сме проверили, че herbivore всъщност сочи към Заек е безопасно да кастнем към Заек.
                // тъй като r е от тип Заек може да извикваме методите на заек.
                r.DoZigZag();
            }
            else if (herbivore is Fox)
            {
                // съкратена версия на предното
                ((Fox)herbivore).StealTheCheese();
            }
            else if (herbivore is Elephant el)
            {
                // още по-съкратена версия на предното.
                el.DrinkFromTheNose();
            }

            // директното кастване е опасно: ((Fox)herbivore).StealTheCheese();
            // Използва се само ако преди това сме направили проверка дали наистина обекта е такъв, какъвто ние очакваме: if (herbivore is Fox)
            // В противен случай програмата ще гръмне ако не сме уцелили правилният тип

            //Втори вариант на кастване - ключова дума "as" :
            Fox fox = herbivore as Fox;

            if (fox == null)
            {
                // резултат 1: herbivore не е от тип лисица и няма как да бъде третиран като такава. Променливата Fox ще сочи към нищото.
                // При такъв вид кастване трябва винаги да се провери дали променливата не е null.
                Console.WriteLine("This herbivore is not a fox");
            }
            else
            {
                //резултат 2: успешно успяхме да кастнем към лисица, това означава, че обекта herbivore всъщност е лисица.
                // и сега чрез променливата fox може да викаме методи характерни само за лисица.
                fox.StealTheCheese();
            }


            //Всяка променлива от референтен тип А може:
            Fox        f        = new Fox();    //да сочи към обект от тип А
            IHerbivore herb     = new Rabbit(); //, обект, който наследява А
            Elephant   elephant = null;         //или към нищо (null)
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Fox");
            Fox fox = new Fox();

            Console.WriteLine("from Carnivore");
            Console.WriteLine(fox.Eat());
            Console.WriteLine("from Animal");
            Console.WriteLine(fox.Health());
            Console.WriteLine("from DemiGod");
            Console.WriteLine(fox.SuperPower());
            Console.WriteLine("from IHunt");
            Console.WriteLine(fox.Weapon());

            Console.WriteLine();

            Console.WriteLine("Panda");
            Panda panda = new Panda();

            Console.WriteLine("from Herbivore");
            Console.WriteLine(panda.Eat());
            Console.WriteLine("from Animal");
            Console.WriteLine(panda.Health());
            Console.WriteLine("from DemiGod");
            Console.WriteLine(panda.SuperPower());

            Console.WriteLine();

            Console.WriteLine("Tiger");
            Tiger tiger = new Tiger();

            Console.WriteLine("from ISleep");
            Console.WriteLine(tiger.Nap());
            Console.WriteLine("from Carnivore");
            Console.WriteLine(tiger.Eat());
            Console.WriteLine("from Animal");
            Console.WriteLine(tiger.Health());
            Console.WriteLine("from DemiGod");
            Console.WriteLine(tiger.SuperPower());

            Console.WriteLine();

            Console.WriteLine("Fox");
            Youkai youkai = new Youkai();

            Console.WriteLine("from Panda");
            Console.WriteLine(youkai.Name());
            Console.WriteLine("from Herbivore");
            Console.WriteLine(youkai.Eat());
            Console.WriteLine("from Animal");
            Console.WriteLine(youkai.Health());
            Console.WriteLine("from DemiGod");
            Console.WriteLine(youkai.SuperPower());
            Console.WriteLine("from IHunt");
            Console.WriteLine(youkai.Weapon());
            Console.WriteLine("from ISleep");
            Console.WriteLine(youkai.Asleep);

            Console.WriteLine();

            Console.WriteLine("Animal");
            Animal animal = new Animal();

            Console.WriteLine("from DemiGod");
            Console.WriteLine(fox.SuperPower());

            Console.WriteLine();
        }