Skip to content

Instantly share code, notes, and snippets.

@bcatcho
Last active December 25, 2015 09:39
Show Gist options
  • Save bcatcho/6955601 to your computer and use it in GitHub Desktop.
Save bcatcho/6955601 to your computer and use it in GitHub Desktop.
Read the Readme.md near the bottom

Read first

If you really wanted to enforce your LocalSerializer class to be used in a specific way without allowing other classes to use it directly, you can try employing double-dispatch. It's not a frequently used pattern and has some code-bloating side effects if you aren't careful.

To see the magic, start at DataManager.OnEnable()

Note, in the example below:

  • There is no way to use your serializer without a DataManager. This will help guide the user of the API as well as restrict them. Furthermore, I made sure not to make an interface for the DataManager. Serializers should use THE DataManager, not just any subclass.

  • DataManager is sealed : This prevents the user from subclassing to get around your API rules. This is overkill

  • LocalSerializers and DataManagers are fairly coupled. Changes in one will need to be propagated to the others.

public class LocalSerializer: ILocalSerializer
{
public void LoadSomeStuff(DataManager dataManager)
{
/* Pretend this loads resources*/
List<Resources> resources = Resources.Load("thestuff.ini");
manager.LoadResources(resources);
}
}
// Sealed, so that users can't subclass it.
public sealed class DataManager : Monobehaviour
{
// !!! Start here. This is where the magic begins to happen.
void OnEnable()
{
var serializer = (ILocalSerializer)FindObjectOfType(typeof(ILocalSerializer));
serializer.LoadResources(this);
}
public void LoadResources(IEnumerable<Resources> resources)
{
/* do somehting with the resources */
}
}
public interface ILocalSerializer
{
void LoadResources(DataManager dataManager);
}
@bcatcho
Copy link
Author

bcatcho commented Oct 12, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment