Last active
May 8, 2017 22:24
-
-
Save Geri-Borbas/8c01cda2109cda0af4cbce880499f82a to your computer and use it in GitHub Desktop.
💡 Some notes on a more flexible, maintainable event dispatching method than using if or switch statements all around. Also, different dispatch rules can be easily plugged in and out.
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
// | |
// Copyright (c) 2017 eppz! mobile, Gergely Borbás (SP) | |
// | |
// http://www.twitter.com/_eppz | |
// | |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, | |
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A | |
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT | |
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF | |
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE | |
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
// | |
using UnityEngine; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
namespace Game | |
{ | |
public class Object : MonoBehaviour | |
{ | |
public enum State { Default, On, Off, Suspended } | |
public State state; | |
Dictionary<State, Action> methodsForStates; | |
void Awake() | |
{ | |
methodsForStates = new Dictionary<State, Action>() | |
{ | |
{ State.Default, Reset }, | |
{ State.On, () => Turn(true) }, | |
{ State.Off, () => Turn(false) }, | |
{ State.Suspended, () => | |
{ | |
Reset(); | |
Suspend(); | |
} | |
} | |
}; | |
} | |
void SetState(State state) | |
{ | |
this.state = state; // Set | |
methodsForStates[state](); // Action(s) | |
} | |
void Reset() | |
{ | |
// Awesome implementation. | |
} | |
void Turn(bool isOn) | |
{ | |
// Clever method. | |
} | |
void Suspend() | |
{ | |
// Neat behaviour. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment