특정한 동작에 대해 클래스 내부에 대한 수정이 아니라 클래스 외부에서 수정하도록 설계 해둔 패턴!

인터페이스 또는 델리게이트를 사용하여 구현할 수 있겠습니다.

 

using System;

namespace ConsoleApp
{
    class Program
    {
        public static void Main (string[] args)
        {
            Unit marine = new Unit();
            Unit zerling = new Unit();
            Unit medic = new Unit();

            marine.SetAttack(new Marine());
            zerling.SetAttack(new Zergling());
            medic.SetHeal(new Medic());

            marine.Attack();
            marine.Heal();

            zerling.Attack();
            zerling.Heal();
            
            medic.Attack();
            medic.Heal();
        }
    }

    class Unit
    {
        private IAttack attack = null;
        private IHeal heal = null;

        public void Attack ()
        {
            if (attack != null)
            {
                attack.Attack();
            }
        }

        public void Heal ()
        {
            if (heal != null)
            {
                heal.Heal();
            }
        }

        public void SetAttack (IAttack attack)
        {
            this.attack = attack;
        }

        public void SetHeal (IHeal heal)
        {
            this.heal = heal;
        }
    }

    interface IAttack
    {
        void Attack();
    }

    interface IHeal
    {
        void Heal();
    }

    class Marine : IAttack
    {
        public void Attack ()
        {
            Console.WriteLine("가우스 라이플 공격");
        }
    }

    class Zergling : IAttack
    {
        public void Attack()
        {
            Console.WriteLine("발톱 공격");
        }
    }

    class Medic : IHeal
    {
        public void Heal ()
        {
            Console.WriteLine("치료");
        }
    }
}

 

실행 결과

 

+ Recent posts