Created
June 10, 2016 18:13
-
-
Save ShirakawaYoshimaru/578ed2dafcb9bc7ae2502fc540d83576 to your computer and use it in GitHub Desktop.
This file contains 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
using UnityEngine; | |
using UnityEngine.UI; | |
using System; | |
//使い方 | |
public class TestScript : MonoBehaviour | |
{ | |
public View view; | |
Data<int> score = new Data<int> (); | |
void Start () | |
{ | |
//viewに観察対象を渡す | |
view.Init (score); | |
//dataを更新する | |
score.ChangeValue (100); | |
} | |
} | |
//観察者のinterface | |
public interface IObserver<T> | |
{ | |
void Update (T value); | |
} | |
//観察対象者のinterface | |
public interface IObservable<T> | |
{ | |
void ChangeValue (T value); | |
void AddObserver (IObserver<T> observer); | |
} | |
//観察対象の実装 | |
public class Data<T> : IObservable<T> | |
{ | |
private T value; | |
private IObserver<T> observer; | |
public void ChangeValue (T value) | |
{ | |
this.value = value; | |
observer.Update (this.value); | |
} | |
public void AddObserver (IObserver<T> observer) | |
{ | |
this.observer = observer; | |
} | |
} | |
//観察者の実装 | |
public class View : MonoBehaviour, IObserver<int> | |
{ | |
public Text scoreText; | |
public void Init (Data<int> scoreData) | |
{ | |
scoreData.AddObserver (this); | |
} | |
public void Update (int value) | |
{ | |
scoreText.text = "Score:" + value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment