Dowemo

Gof:

"define a connection between objects, and when an object tra form state, other associated objects automatically receive notifications. "

In reality, social networking is an example.

The previous newspaper, every time a new journal is released,

A newspaper will send a new journal to the hand of a subscription.

So, every time a new journal comes out, the newspaper must be sent to each person 's hand.

And today 's webo is an application of observer mode.

When you want to focus on a person, you can subscribe to a single person only

When people update webo, only need to update to the webo platform.

People who subscribe can receive updated messages

People who don't need to be concerned send messages to each subscriber.

Event system ( event ) in c # is an observer mode used.

All events in unity ( such as UI click events ) are also the observer patterns.





//事件接口


public abstract class Subject {


 List<Observer> m_Observers = new List<Observer>();



 public void Attach(Observer theObserver) {


 m_Observers.Add(theObserver);


 }



 public void Detach(Observer theObserver) {


 m_Observers.Remove(theObserver);


 }



 public void Notify() {


 foreach (Observer theObserver in m_Observers)


 theObserver.Update();


 }


}









//实现事件


public class ConcreteSubject : Subject {


 string m_SubjectState;



 public void SetState(string state) {


 m_SubjectState = state;


 Notify();


 }



 public string GetState() {


 return m_SubjectState;


 }


}









//观察者接口


public abstract class Observer {


 public abstract void Update();


}









//实现观察者


public class ConcreteObserver : Observer {


 string m_SubjectState;



 ConcreteSubject m_Subject = null;



 public ConcreteObserver(ConcreteSubject theSubject){


 m_Subject = theSubject;


 }



 public override void Update()


 {


 Debug.Log("ConcreteSubject.Update");


 }


}









//测试类


public class TestObserver {


 private void UnitTest() {


 ConcreteSubject theSubject = new ConcreteSubject();



 ConcreteObserver theObserver = new ConcreteObserver(theSubject);


 theSubject.Attach(theObserver);



 theSubject.SetState("Subject状态1");


 }


}





The design principle of the observer pattern is to set up a theme ( subject )

You can also notify the viewer/subscriber of this topic when it's published.

And the subject doesn't have to be able to do what the viewer/subscriber will do next

The main features and advantages of the observer pattern:

The two actio & that take place in the subject and function are deactivated.

The article the book"design pattern and game perfect development".




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs