Custom Registries

From OrbEdit Wiki

Jump to: navigation, search

Custom Registries

Instance or Original?

One important decision you must make when creating a Registry is whether the Registry will return original objects or instances. If your Registry returns originals, it is acting as a simple container; every time you call get(), you will get the same object. However, if your Registry returns instances, it is acting as more of a factory; every time you call get(), you will get a copy of the original object.

This decision comes down to how you wish to use the object. Consider the FontRegistry: multiple Sprites can safely use the same Font, so there's no harm in returning the original Font each time you call FontRegistry:get("Arial12");. However, the ItemRegistry should return instances since you do not want your game's characters sharing the same item.

So how is this accomplished? When the base Registry:get() method is called, it first looks for a method called copy in the retrieved object. If it finds a method by this name, it calls it and returns the result. If it does not find it, it goes ahead and returns the retrieve object. So if you need an instance, rather than the original, simply make sure your objects implement a copy() method.