유니티3D 프로그래밍

C# 3주차 1일 수업 내용 : Delegate, Callback (21.03.22) 본문

C#/수업내용

C# 3주차 1일 수업 내용 : Delegate, Callback (21.03.22)

tjdgus9955 2021. 3. 22. 10:50

Delegate

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    {    
        //1. 델리게이트 선언
        public delegate void Del(string massage);
        //생성자 
        public App()
        {
            //3. 델리게이트 인스턴스화 (델리게이트에 메서드 연결)
            Del handler = this.DeligateMethod;

            //4. 델리게이트 호출
            //handler("Hello World!");
            MathodWithCallback(handler);
  
        }

        //2. 델리게이트 메서드 정의
        public void DeligateMethod(string massage)
        {
            Console.WriteLine(massage);
        }

        //콜백 메서드 정의
        public void MathodWithCallback(Del callback)
        {
            callback("Hello World");
        }
 
    }
}

 

 

Button Delegate

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    { 
        //생성자 
        public App()
        {
            Console.WriteLine("App");
            Button btn = new Button();
            //버튼을 불렀다면 알려줘
            btn.onClick = this.OnClickButton;
            
            //유저가 버튼을 눌렀다.
            btn.OnClick();
            
            
        }
        private void OnClickButton()
        {
            //설정 팝업을 연다.
            Console.WriteLine("설정 팝업을 엽니다.");
        }
 
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public delegate void DelButtonOn();
    public class Button
    {
        public DelButtonOn onClick;

        //생성자
        public Button()
        {

        }

        public void OnClick()
        {
            Console.WriteLine("버튼을 클릭합니다.");
            this.onClick();
        }
    }
}

 

Building Delegate

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");
            Building building = new Building();
            //델리게이트 인스턴스화 
            building.onComplete = this.OnComplete;
            //빌드 시작 
            building.Build();
        }

        private void OnComplete()
        {
            Console.WriteLine("건물을 지었습니다.");
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public delegate void DelBuild();
    public class Building
    {
        public DelBuild onComplete;
        //생성자
        public Building()
        {

        }

        public void Build()
        {
            Console.WriteLine("건물을 짓습니다.");
            this.onComplete();
        }
    }
}

 

FileManager Delegate

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");

            FileManager fm = new FileManager();
            fm.onOpenComple = this.OnOpenComplete;
            fm.Open("C:\\test.txt");

        }

        public void OnOpenComplete()
        {
            Console.WriteLine("파일을 열었습니다.");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public delegate void DelFile();
    public class FileManager
    {
        public DelFile onOpenComple;
        public FileManager()
        {

        }

        public void Open(string filePath)
        {
            Console.WriteLine(filePath + " 에 있는 파일을 엽니다.");
            this.onOpenComple();
        }
    }
}

SceneManager Delegate

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");
            SceneManager sm = new SceneManager();
            //델리게이트 인스턴스화
            sm.onLoaded = this.OnLoaded;
            //메서드 호출
            sm.LoadScene("Lobby");

        }

        public void OnLoaded()
        {
            Console.WriteLine("장면을 불러왔습니다.");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public delegate void DelScene();
    public class SceneManager
    {
        public DelScene onLoaded;
        //생성자
        public SceneManager()
        {
            
        }

        public void LoadScene(string scene)
        {
            Console.WriteLine(scene + " 장면을 불러옵니다.");
            this.onLoaded();
        }

    }
}

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");

            GameLauncher launcher = new GameLauncher();
            launcher.onEndGame = this.OnEndGame;
            launcher.StartGame();

        }

        public void OnEndGame()
        {
            Console.WriteLine("게임을 종료합니다.");
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public delegate void DelGame();
    public class GameLauncher
    {
        public DelGame onEndGame;
        public GameLauncher()
        {

        }

        public void StartGame()
        {
            Console.WriteLine("게임을 시작합니다.");
            this.onEndGame();
        }
    }
}

Book Delegate

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    {
        //생성자 
        public App()
        {
            Console.WriteLine("App");
            BookDB bookDB = new BookDB();
            bookDB.AddBook("해리포터", 10050, true);
            bookDB.AddBook("니클의 소년들", 14000, false);
            bookDB.AddBook("멋진 신세계", 8200, true);

            //bookDB.ProscessPaperbackBooks(PrintTitle);
            bookDB.ProcessBooks(false, PrintTitle);

            PriceTotaller totaller = new PriceTotaller();
            bookDB.ProcessBooks(true, totaller.AddBookToTotal);
            Console.WriteLine("{0} {1}", totaller.CountBook, totaller.PriceBook);

            bookDB.FindBookByName("해리포터", FoundBook);
        }

        private void FoundBook(string title)
        {
            if(string.IsNullOrEmpty(title))
            {
                Console.WriteLine("책을 찾을 수 없습니다.");
            }
            else
            {
                Console.WriteLine("{0}을 찾았습니다.", title);
            }            
        }
       private void PrintTitle(Book book)
        {
            Console.WriteLine("{0}, {1}, {2}", book.title, book.price, book.paperBack);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public struct Book
    {
        public string title;
        public int price;
        public bool paperBack;
        //생성자
        public Book(string title, int price, bool paperBack)
        {
            this.title = title;
            this.price = price;
            this.paperBack = paperBack;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    //델리게이트 정의 (형식 정의)
    public delegate void ProcessBookCallback(Book book);

    class BookDB
    {
        private List<Book> list;
        //생성자
        public BookDB()
        {
            this.list = new List<Book>();
        }

        //책 추가
        public void AddBook(string title, int price, bool paperBack)
        {
            Book book = new Book(title, price, paperBack);
            this.list.Add(book);
        }

        //종이책을 찾아내서 콜백으로 Book 인스턴스를 전달
        public void ProcessPaperbackBooks(ProcessBookCallback callback)
        {
            foreach(Book book in list)
            {
                if(book.paperBack)
                {
                    callback(book);
                }
            }
        }

        public void ProcessBooks(bool paperback, ProcessBookCallback callback)
        {
            foreach (Book book in list)
            {
                if (book.paperBack == paperback)
                {
                    callback(book);
                }
            }
        }

        public void FindBookByName(string title, Action<string> callback)
        {
            foreach(Book book in list)
            {
                if(book.title == title)
                {
                    callback(book.title);
                   return;
                }
            }
            callback(string.Empty);

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public class PriceTotaller
    {
        public int CountBook { get; private set; }
        public int PriceBook { get; private set; }

        public void AddBookToTotal(Book book)
        {
            this.CountBook += 1;
            this.PriceBook += book.price;
        }
    }
}

 

Hero

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace Study01
{
     
    public class App
    {
        private Hero hero;
        private Popup popup;
        //생성자 
        public App()
        {
            hero = new Hero();
            popup = new Popup();
            popup.Print();
            hero.onAttack = this.OnAttack;
            hero.Attack();
            hero.Attack();
            hero.Attack();
            hero.Attack();
            hero.Attack();
            hero.Attack();
            hero.Attack();
            hero.Attack();
            hero.Attack();
            hero.Attack();
        }
        private void OnAttack()
        {
            if (popup.IsComplete())
            {
                this.hero.onAttack = null;
            }
            this.popup.UpdateInfo();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    public class Hero
    {
        public Action onAttack;
        public Hero()
        {

        }
        public void Attack()
        {
            Console.WriteLine("놀을 처치 했습니다.");
            if (this.onAttack != null)
            {
                this.onAttack();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study01
{
    class Popup
    {
        public int goal = 8;
        public int count = 0;
        public Popup()
        {

        }
        public bool IsComplete()
        {
            return count >= goal;
        }
        public void Print()
        {
            if (this.IsComplete())
            {
                Console.WriteLine("[완료] 놀 처치 {0}/{1}", this.count, this.goal);
            }
            else
            {
                Console.WriteLine("놀 처치 {0}/{1}", this.count, this.goal);
            }
        }

        public void UpdateInfo()
        {

            if (this.count >= this.goal)
            {
                return;
            }

            this.count++;
            this.Print();
        }
    }
}