본문 바로가기

카테고리 없음

SMART FACTORY -C# Delegate -> 더욱 간단하게 유지 보수 가능한 방법

반응형

 

using System;

namespace ConsoleApp3
{
    delegate int CalcDelegate(int x, int y);
    delegate void WorkDelegate(char arg1, int arg2, int arg3);
    
    class MessageMap
    {
        public char opCode;
        public CalcDelegate calc;
        public MessageMap(char opCode, CalcDelegate calc)
        {
            this.opCode = opCode;
            this.calc = calc;
        }
    }
    public class Mathematics
    {
        
        MessageMap[] amessegemap;
        static int Add(int x, int y) { return x + y; }
        static int Sub(int x, int y) { return x - y; }
        static int Mul(int x, int y) { return x * y; }
        static int Div(int x, int y) { return x / y; }
        static int Per(int x, int y) { return x % y; }


        public Mathematics()
        {

            amessegemap = new MessageMap[]
            {
                new MessageMap('+',Add),
                new MessageMap('-',Sub),
                new MessageMap('*',Mul),
                new MessageMap('/',Div),
                new MessageMap('%', Per)
            };  
        }  
        public void Calculate(char opCode, int operand1, int oprand2)  //이렇게 하는게 유지 보수가 쉽고 코드가 늘어나지않는다.
        {            
            Console.Write(opCode +" : " );
            foreach (MessageMap temp in amessegemap)
            {
                if (temp.opCode == opCode)
                {
                    Console.WriteLine(temp.calc(operand1, oprand2));
                }     
            }
        }

        class Program
        {
           
            static void Main(string[] args)
            {
                Mathematics mathematics = new Mathematics();
                WorkDelegate workDelegate = mathematics.Calculate;
                workDelegate('+', 10, 5);
                workDelegate('-', 10, 5);
                workDelegate('*', 10, 5);
                workDelegate('/', 10, 5);
                workDelegate('%', 10, 6);
            }
        }
    }
}

 

 

 

 

 

 

파이선에서는 딕션너리라는 방법으로 쉽게 코딩할 수 있다..! 

 

반응형