20160519 C#

C, C++ 2016. 5. 19. 15:52

# delegate


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using vooo_characterInfo;
 
namespace Test
{
    class DefenseMachine
    {
        public string name;
        private GameWorld refWorld;
 
        public DefenseMachine(GameWorld world)
        {
            refWorld = world;
 
            // += 다중위임.
            // GameWorld 클래스의 delegate 객체에 observer의 메소드를 등록함.
            // 이렇게 해두면 GameWorld에서 observer의 메소드를 실행할 수 있게 된다.
            refWorld.dgObject += new GameWorld.dg_ThereIsSomeone(ThereIsSomeone);
        }
 
        public void ThereIsSomeone()
        {
            Console.WriteLine(name + " said, enemies are coming");
        }
 
        public void update()
        {
            Console.WriteLine("name : " + name);
        }
    }
 
    class GameWorld
    {
        public ArrayList gameObjects = new ArrayList();
 
        // 위임
        public delegate void dg_ThereIsSomeone();
 
        // 위임 객체
        public dg_ThereIsSomeone dgObject;
 
        public void update()
        {
            int nCountOfObjects = gameObjects.Count;
            for(int i = 0; i < nCountOfObjects; i++)
            {
                ((DefenseMachine)gameObjects[i]).update();
            }
 
            Random r = new Random();
            int nReturn = r.Next(100);
            if(nReturn > 80)
            {
                if(dgObject != null)
                {
                    Console.WriteLine("Subject에 연결된 Observer의 수 : " + dgObject.GetInvocationList().Length);
 
                    // 등록된 observer들에게 알린다. 즉, delegate에 연결된 메소드들을 실행시킨다.
                    dgObject();
                }
            }
        }
 
    }
 
    class Program
    {
        
        static void Main(string[] args)
        {
            GameWorld gameWorld = new GameWorld();
            DefenseMachine machineA = new DefenseMachine(gameWorld);
            machineA.name = "robot A";
            DefenseMachine machineB = new DefenseMachine(gameWorld);
            machineB.name = "robot B";
            DefenseMachine machineC = new DefenseMachine(gameWorld);
            machineC.name = "robot C";
 
            gameWorld.gameObjects.Add(machineA);
            gameWorld.gameObjects.Add(machineB);
            gameWorld.gameObjects.Add(machineC);
 
            bool bLoop = true;
            while(bLoop)
            {
                // 1초에 한번씩 update
                Thread.Sleep(1000);
                Console.WriteLine("---- Game Start ----");
                gameWorld.update();
            }
        }
    }
}
 
cs





: