Last active
December 22, 2018 08:55
-
-
Save Curookie/dd48a56b320a68e719d5cf6a5f54ab17 to your computer and use it in GitHub Desktop.
코드 디자인 패턴
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
관찰자 패턴 | |
이벤트 리스트들이 적혀있다. | |
이벤트(상황)를 관찰해서 어떤 이벤트(상황)가 작동하면 이 녀석(관찰자)가 행동한다. | |
혹시 게임 개발 할때 | |
`{.C#}GameObject.Find("BigBoss").GetComponent<BossManager>().AddHealth(-20F);` | |
이런 코드를 남발한다면 관찰자 패턴을 고려해볼 필요가 있다. | |
델리게이트와 옵저버패턴은 비슷하다고 보면 된다. | |
옵저버 패턴은 특정 객체(Subject)의 상태 변화에 따라 특정 객체와 연결된 다른 객체들(Observer)이 영향을 받는 1 : N 관계이다. | |
특정 객체(Subject)의 상태 변화에 따라 영향을 받는 다른 객체들(Observer)이 무수히 많다면 | |
특정 객체에는 다른 객체들의 정보가 무수히 필요하게되며 심각한 경우에는 이 정보들이 옳바르지 못한 곳에 끼어들 수도 있다. | |
이는 결과적으로 결합도를 높이고 응집도를 낮추게된다. C#에서는 delegate, event를 통해 옵저버 패턴을 구현하여 이를 방지한다. | |
옵저버 패턴에도 단점이 있다고 한다. Subject의 코드를 봤을 때 무슨 동작을 하고 있는지 알 수 없기 때문이다. | |
각각의 Observer 들을 보아도 단편적인 것만 알 수 있지 전체적인 틀을 알수 없기는 마찬가지이다. | |
하지만 나는 그만큼 결합도가 낮아진 것이라고 생각하기 때문에 큰 단점이 된다고 생각하지는 않는다. | |
예제 - 스페이스바 클릭 시 적들이 빨간색으로 변하는 상황 | |
Player (Subject) | |
```{.C#} | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Player : MonoBehaviour | |
{ | |
#region Singleton | |
private static Player _instance; | |
public static Player Instance | |
{ | |
get | |
{ | |
if(_instance == null) | |
{ | |
_instance = FindObjectOfType(typeof(Player)) as Player; | |
} | |
return _instance; | |
} | |
} | |
#endregion | |
public delegate void ChangeEnemyColor(Color color); | |
public event ChangeEnemyColor onEnemyHit; | |
void Update () { | |
if(Input.GetKeyDown(KeyCode.Space)) | |
{ | |
if(onEnemyHit != null) | |
{ | |
onEnemyHit(Color.red); | |
} | |
} | |
} | |
} | |
``` | |
Enemy | |
```{.C#} | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Enemy : MonoBehaviour { | |
// Use this for initialization | |
void Start () | |
{ | |
Player.Instance.onEnemyHit += Damage; | |
} | |
public void Damage(Color color) | |
{ | |
GetComponent<Renderer>().material.color = Color.red; | |
} | |
private void OnDisable() | |
{ | |
if (Player.Instance != null) | |
Player.Instance.onEnemyHit -= Damage; | |
} | |
} | |
``` | |
출처 : http://unity-programmer.tistory.com/13 | |
좋은 예제 : http://hhnote.tistory.com/4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment