Observer

In C# we can make use of the observer pattern already at the language level. So completing this task with built in keywords could be done in a few lines of code and would be far too trivial. So to better understand the pattern you will have to implement it without using the built in language level support(This means no events, event handlers, delegates, actions, etc).

The task is to count the number of steps taken by all existing GridMovements. The counting is done in ConsoleStepCounter and UIStepCounter, which will listen to the notifications from the GridMovement.

The counting classes are included in new additional assets. The new assets should be imported into your already existing project. To import the base code into project go to Assets > Import > Custom Package or run the *.unitypackage file. The package can be downloaded  here

After importing the package you should find the ConsoleStepCounter and UIStepCounter prefabs and add them into the scene. To complete the task you will have to finish the classes Subject,  ConsoleStepCounter  and UIStepCounter. You will also have to update the GridMovement, so it would notify listeners whenever a successful move is made. There are more details in the comments of the base package.

The Subject and GridMovement classes have one major variation from the classical way the structure of this pattern is presented. Generally classes expand the subject class to make use of it, but we are not able to do this when working with Unity. This is due to C# lacking multiple inheritance from classes. Creating a ObservableMonoBehaviour would also be an option, but OOP principles recommend use of composition instead of inheritance, so let's go with that instead.

To do this add a Subject type variable to the GridMovement class and create an instance in the Awake method. As observer pattern usually has the sender object as part of the notification methods parameters, we will also forward the GridMovement reference for later use in Subject class. In other words, as GridMovement does not extend subject, we can not send "this" as sender in the subject class. In code it would look something like the following illustration.

  

 

 

TODO checklist:

  • Download and import the new package
  • Add UIStepCounter and ConsoleStepCounter prefabs to your scene.
  • Implement the Subject class
  • Use the Subject class in GridMovement to notify all observers of successful movements.
  • Implement the Start methods of UIStepCounter and ConsoleStepCounter to register observers.
  • Implement the OnDestroy methods of UIStepCounter and ConsoleStepCounter to deregister observers.

 

 

;