dimanche 28 avril 2019

C# Implement Observable Pattaern

I`m trying to implement observable pattern using C#. In my sample code I have two kind of soldiers archer two classes: Archer and Swordsman they implement Soldier interface. Soldier interface has has four methods:

  • Attack() - command the soldier to attack the enemy
  • Died() - this method doesn`t matter in that example
  • Kill() - command our soldier to kill the enemy
  • BattleCry() - celebration of ALL my soldiers after emeny is killed

and one property bool IsEnemyKilled - when Kill() method is called IsEnemyKilled becomes true.

And here is what I want to do: I know that to implement Observer Pattern I need Provider and Observers. When one of soldiers e.g. archer - kills an enemy archer.Kill();. IsEnemyKilled become true (this is my provider) and all my other soldiers (my observers) e.g. swordsman and another archer must be notified that IsEnemyKilled is true and they must call BattleCry().

I`m confused how to do it. I will appreciate if anyone suggest in idea. Here is my sample code.

namespace ImplementObservable
{
    class Program
    {
        static void Main(string[] args)
        {

            var archer = new Archer();
            var swordsman = new Swordsman();
            archer.Attack();
            archer.Kill();
            Console.ReadKey();
        }
    }

    public class Archer : Soldier
    {
        bool IsEnemyKilled;
        // watch somehow prop "IsEnemyKilled" and if it changes to true call BattleCry() for all units

        public void Attack()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Archer attack!");
        }

        public void Died()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Archer died :(");
        }

        public void Kill()
        {
            IsEnemyKilled = true;
            Console.WriteLine("Archer killed enemy! Hurray!!");
        }

        public void BattleCry()
        {
            Console.WriteLine("Archer: Go for victory !");
        }
    }

    public class Swordsman : Soldier
    {
        bool IsEnemyKilled;
        // watch somehow prop "IsEnemyKilled" and if it changes to true call BattleCry() for all units

        public void Attack()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Swordsman attack!");
        }

        public void Died()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Swordsman died :(");
        }
        public void Kill()
        {
            IsEnemyKilled = true;
            Console.WriteLine("Swordsman killed enemy! Hurray!!");
        }

        public void BattleCry()
        {
            Console.WriteLine("Swordsman: Go for victory !");
        }
    }

    public interface Soldier
    {
        void Kill();

        void Attack();

        void Died();

        void BattleCry();
    }
}

Aucun commentaire:

Enregistrer un commentaire