Proxy Pattern (구조패턴 : 프록시패턴)

Design Patterns 2019. 2. 28. 11:43
반응형
디자인패턴이란?

소프트웨어 디자인에서 특정 문맥에서 공통적으로 발생하는 문제에 대해 재사용 가능한 해결책 

소프트웨어 설계에서 특정 맥락에 자주발생하는 고질적 문제들이 발생했을때 재사용할수 있는 방법 

GoF디자인패턴 
3가지 구조(생성, 행위, 구조)

Proxy Pattern (프록시 패턴 / 구조패턴)

액션을 취하는 객체의 대리자 역활을 한다.
1. 객체를 생성가능.
2. 액세스 권한
3. 메모리를 절약


카메라 Projection , order in layer는 상관없음 

Perspective + Physics.Raycast :  O
Orthographic + Physics.Raycast :   O


Perspective + Physics2D.Raycast : X
Orthographic + Physics2D.Raycast :  O

Perspective + Physics2D.GetIntersection : X
Orthographic + Physics2D.GetIntersection  :  O

Perspective , Physics2D : 예측 가능한대로 실행되지 않음 ??, 왜???






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
101
102
103
104
105
106
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.StyleSheets;
using UnityEngine;
 
public class GameEnums
{
    public enum eZergUnitType
    {
        NONE = -1,
        DRONE,
    }
}
 
public class App : MonoBehaviour
{
    private Cocoon cocoon;
    private Hatchery hatchery;
    private  List<IZerg> zergUnits = new List<IZerg>();
 
    
    public static App Instance;
 
    void Awake()
    {
        App.Instance = this;
 
        EventDispatcher.GetInstance().AddEventListener("CreateDroneEvent", EventDispatcher.GetInstance().TestEventHandler, (sender, e) =>
        {
            Debug.Log("<color=red>1</color>");
            var args = e as Cocoon.CocoonEventArgs;
            this.zergUnits.Add(args.drone);
            Debug.LogFormat("{0} / 200"this.zergUnits.Count);
        });
 
        EventDispatcher.GetInstance().AddEventListener("DroneDieEvent", EventDispatcher.GetInstance().TestEventHandler, (sender, e) =>
        {
            Debug.Log("<color=red>APP: DroneDieEvent</color>");
        });
 
    }
 
    void Start()
    {
 
        //해처리 생성
        var hatcheryPrefab = Resources.Load<GameObject>("hatchery");
        var hatcheryGo = Instantiate(hatcheryPrefab);
        hatchery = hatcheryGo.GetComponent<Hatchery>();
        hatchery.Init();
 
 
       
    }
 
    void OnGUI()
    {
        if (GUILayout.Button("킬 드론", GUILayout.Width(100), GUILayout.Height(60)))
        {
            var dron = zergUnits[0as Drone;
            dron.Die();
        }
    }
 
    void Update()
    {
        //마우스클릭 했을때 Ray발사 
        if (Input.GetMouseButtonUp(0))
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red, 10);
            //충돌검사 
            //var hit = Physics2D.Raycast(ray.origin, ray.direction, 1000);
            //var arrHit = Physics2D.GetRayIntersectionAll(ray, 100);
            //var hit = Physics2D.GetRayIntersection(ray, 1000);
            var hit = Physics2D.Raycast(ray.origin, ray.direction, 1000);
 
            //foreach (var hit in arrHit)
            //{
            //    Debug.Log(hit.collider.tag);
            //}
            if (hit)
            {
                //충돌 되었다면 
                if (hit.collider.tag == "Larva")
                {
                    Debug.LogFormat("{0}, {1}", hit.collider.tag, hit.collider.gameObject.GetHashCode());
                    this.cocoon = hatchery.GetCocoon(hit.collider.gameObject.GetHashCode());
                    Debug.LogFormat("cocoon: {0}"this.cocoon);
                }
            }
        }
 
 
        if (Input.GetKeyUp(KeyCode.D))
        {
            if (this.cocoon != null)
            {
                var dron = this.cocoon.CreateUnit(GameEnums.eZergUnitType.DRONE);
                dron.Move(new Vector3(1,1,1));
            }
        }
    }
}
 
cs



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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Hatchery : MonoBehaviour
{
    private Vector3[] cocoonsInitPosList = {
        new Vector3(-2.63f, -2.34f, 0),
        new Vector3(-0.14f, -2.77f, 0),
        new Vector3(2.18f, -2.02f, 0),
    };
 
    void Awake()
    {
        //인스턴스화 직후 호출됨 
    }
 
    void Start()
    {
        //인스터스화 직후 업데이트 전 
    }
 
    void OnEnable()
    {
        //오브젝트 활성화 직후 
    }
 
    //해처리 초기화 메서드 
    public void Init()
    {
        EventDispatcher.GetInstance().AddEventListener("DroneDieEvent", EventDispatcher.GetInstance().TestEventHandler, (sender, e) =>
        {
            Debug.Log("<color=red>Hatchery: DroneDieEvent</color>");
        });
 
        EventDispatcher.GetInstance().AddEventListener("CreateDroneEvent", EventDispatcher.GetInstance().TestEventHandler, (sender, e) =>
        {
            Debug.Log("<color=red>2</color>");
            var cocoonEventArgs = e as Cocoon.CocoonEventArgs;
            if (this.dicCocoon.ContainsKey(cocoonEventArgs.hashCode))
            {
                this.dicCocoon.Remove(cocoonEventArgs.hashCode);
                Debug.LogFormat("라바 수: {0}"this.dicCocoon.Count);
            }
        });
 
 
        //라바를 생성 
        for (int i = 0; i < 3; i++)
        {
            var cocoon = new Cocoon();
            cocoon.model.transform.position = this.cocoonsInitPosList[i];
            Debug.LogFormat("{0}, {1}", cocoon.model.GetHashCode(), cocoon);
            this.dicCocoon.Add(cocoon.model.GetHashCode(), cocoon);
        }
 
        var creepPrefab = Resources.Load<GameObject>("creep");
        var creepGo = GameObject.Instantiate(creepPrefab);
        Debug.Log("creep이 생성되었습니다.");
 
        
    }
 
    private Dictionary<int, Cocoon> dicCocoon = new Dictionary<int, Cocoon>();
 
    public Cocoon GetCocoon(int hashCode)
    {
        return this.dicCocoon[hashCode];
    }
}
 
cs




1
2
3
4
5
6
7
8
9
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public interface IZerg
{
    void Move(Vector3 pos);
}
 
cs



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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
 
//프록시 클래스 
public class Cocoon : IZerg
{
    public class CocoonEventArgs:EventArgs
    {
        public int hashCode;
        public IZerg drone;
        public CocoonEventArgs(int hashCode, IZerg drone)
        {
            this.hashCode = hashCode;
            this.drone = drone;
        }
    }
 
    
 
    public GameObject model;
    
 
 
    public Cocoon()
    {
        //생성자 
        Debug.Log("Cocoon이 생성되었습니다.");
        var larvaPrefab = Resources.Load<GameObject>("larva");
        this.model = GameObject.Instantiate(larvaPrefab);
    }
 
    //override IZerg method
    public void Move(Vector3 pos)
    {
        throw new System.NotImplementedException();
    }
 
    public IZerg CreateUnit(GameEnums.eZergUnitType unitType)
    {
        IZerg unit = null;
 
        switch (unitType)
        {
            case GameEnums.eZergUnitType.DRONE:
            {
                unit = new Drone(this.model.transform.position);
 
                this.OnCreateDroneEvent(new CocoonEventArgs(this.model.GetHashCode(), unit));
 
                GameObject.Destroy(this.model);
 
                
            }
            break;
        }
 
        return unit;
    }
 
    private void OnCreateDroneEvent(CocoonEventArgs args)
    {
        EventDispatcher.GetInstance().DispatchEvent("CreateDroneEvent", args);
    }
 
}
 
cs





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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Drone : IZerg
{
    public GameObject model;
 
    public Drone(Vector3 initPos)
    {
        //생성자 
        var prefab = Resources.Load<GameObject>("drone");
        this.model = GameObject.Instantiate(prefab);
        this.model.transform.position = initPos;
    }
 
    public void Move(Vector3 pos)
    {
        Debug.LogFormat("{0}로 이동했습니다.", pos);
    }
 
    public void Die()
    {
        EventDispatcher.GetInstance().DispatchEvent("DroneDieEvent", EventArgs.Empty);
    }
}
 
cs



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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using UnityEngine;
using static Cocoon;
 
public class EventDispatcher
{
    private static EventDispatcher Instance;
    public EventHandler<EventArgs> TestEventHandler;
 
    public EventDispatcher()
    {
        if (EventDispatcher.Instance != null)
        {
            throw new Exception("싱글톤 클래스입니다.");
        }
    }
 
    public static EventDispatcher GetInstance()
    {
        if(EventDispatcher.Instance == null)
            EventDispatcher.Instance = new EventDispatcher();
 
        return EventDispatcher.Instance;
    }
 
    public Dictionary<string, EventHandler<EventArgs>> dicEventHandler = new Dictionary<string, EventHandler<EventArgs>>();
 
    //이벤트 핸들러 등록 
    public void AddEventListener(string eventName, EventHandler<EventArgs> handler, EventHandler<EventArgs> executeHandler) 
    {
        if (!dicEventHandler.ContainsKey(eventName))
        {
            dicEventHandler.Add(eventName, handler);
            dicEventHandler[eventName] = handler;
            Debug.LogFormat("이벤트 핸들러 등록", handler);
        }
 
        dicEventHandler[eventName] += executeHandler;
    }
 
    //이벤트 발송 
    public void DispatchEvent(string eventName, EventArgs e)
    {
        var handler = dicEventHandler[eventName];
        handler.Invoke(EventDispatcher.GetInstance(), e);
    }
}
 
cs




반응형

'Design Patterns ' 카테고리의 다른 글

State Pattern  (0) 2021.10.18
[Design Pattern] abstract factory pattern  (0) 2020.11.09
Decorator Pattern 실전  (0) 2011.10.10
Decorator Pattern 워밍업  (0) 2011.10.10
Observer Pattern in Java Convert to AS3  (0) 2011.10.09
: