Question

I have an application which will be using large numbers of assets. In order to better handle that I chose to use a registry to hold all the assets so they are accessible across the entire application:

package  
{
    public class SpriteRegistry 
    {
        public static var SPRITENAME = "link to image file";    

        public function SpriteRegistry() 
        {

        }

    }

}

What I would like to do is create an XML document and list off the file name and link so that when the application starts, this registry creates its variables which are freely accessible from that list without me needing to hard code any content directly into it.

Specifically what I need to know is how to get the "public static" effect or how to get an equivalent effect for variables that I CAN dynamically produce.

More info:

I am using a function that loads a sprite texture into a sprite object based on a string variable called mouseAttribute:

loadGraphic(SpriteRegistry[currentAttribute+"Texture"]);

Basically it's like a painting program but for a level editor for a video game.

The problem is that I'm eventually going to have 100+ sprites that I need to application to load and then I need the loadGraphic function to still be able to point effectively to the target sprite.

The library I'm using also needs me to embed the source into a class before I can pull it into the sprite object:

[Embed(source = "/Images/GridTile.png")]
public static var gridTileTexture:Class;

The reason I'm trying to avoid an array is because it means that I will have to search through an array of 100+ objects to find one sprite every time I click a single grid on the editor. That is going to chug.

Was it helpful?

Solution

It's very simple - just use a static function, which will return the XML. So you will need to load the XML file somehow (you decide where, but your registry class should have reference to it). Something similar to this:

private static var _xml:XML;

public static function initialize(xml:XML):void {
    _xml = xml;
}

public static function getXML():XML {
    return _xml;
}

So you will use it like that:

SpriteRegistry.initialize(loadedXML); // done only once when you initialize your app
trace(SpriteRegistry.getXML().someValue); // someValue is directly from the XML

It's a common used strategy and most of the times you would have something like an app initializer - something to load and instantiate all the things, then pass them to some registries that keep them stored for faster and global usage.

Edit: After reading your further comments, I can't see any big change - everything would be ok with this resolution. If you are worried about the 'need to search through array' - just do it as an object! This way you will be able to directly access the proper one using a key exactly like you pointed:

private static var _registry:Object;

public static function initialize(xml:XML):void {
    // loop through xml and insert items
    _registry[key] = resource;
}

public static function getResource(id):Object {
    return _registry[id];
}

This way you can use it like:

SpriteRegistry.getResource(currentAttribute+"Texture");

OTHER TIPS

My personal opinion is that you should avoid statics wherever possible. Instead, you should just create a single instance and provide it through dependency injection where needed.

If you were to go with that approach, you could do something like:

public function getSprite(spriteName:String):Class{
    return this[spriteName];
}

or

public function getSprite(spriteName:String):Class{
    return yourDictionaryOrObject[spriteName];//I'd implement it this way
}

Otherwise you could go with something like:

public static function getSprite(spriteName):Class{
    return ThisHonkingBigUnnchangeableClassname[spriteName];
}

What I would not do is create a Dictionary in a static-only Class, because you're almost inevitably going to wind up with global mutable state.

Discussion, per request

Why would you want to create an instance and pass it, rather than hard-code a reference to a specific Class? A lot of the answers are covered in the global mutable state link above, but here are some that are specific to this kind of problem:

  • Flexibility. Say you build everything with the idea that you'd only have one set of resources being used in parallel, then you discover you need more than one--for example you might need one for color blind users, or multiple languages, or thumbnails vs. full-sized. If you hard-code to a static, then you'll have to go in every place that was hard-coded and make some sort of change to use a different set, whereas if you use DI, you just supply a different instance loaded with different resources, and done.

  • Testability. This is actually covered in the link, but I think it bears pulling out. If you want to run a quick test on something that needs a resource, you have to have that static "thing" and you can't change anything about it. It then becomes very difficult to know if the thing you're actually testing is working or if it just appears to be working based on the current implementation of the "thing."

  • Resource use: everything about an all-static Class exists from the time the swf loads to the time it unloads. Instances only exist from when you instantiate them until they are garbage collected. This can be especially important with resource files that contain embedded assets.

I think the important thing about Frameworks is to realize how they work. The major ones used in ActionScript work the same way, which is they have a central event dispatcher (event bus) that anything loaded to the framework can get a reference to by declaring an interest in it by asking for it to be injected. Additionally, they watch the stage for an event that says that something has been added (in RL it's ADDED_TO_STAGE, whereas in Mate it's the Flex event CREATION_COMPLETE). Once you understand these principles, you can actually apply them yourself with a very light hand without necessarily needing everything that comes along with a framework.

TL;DR

I usually try to avoid answering questions that weren't asked, but in this case I think it would be helpful to discuss an entirely different approach to this problem. At root, the solution comes down not to injecting an entire resource instance, but instead just injecting the resource that's needed.

I don't know what the OP's code is like, but this solution should be general enough that it would work to pass named BitmapDatas to anything that implements our Interface that is capable of dispatching against whatever IEventDispatcher we set as the eventBus (this could be the stage, a particular DisplayObject, or an EventDispatcher that is created just for the purpose.

Note that this code is strikingly similar to code I have in production ;).

public class ResourceManager {
   //this can be loaded dynamically, or you can create subclasses that fill the registry 
   //with embedded Classes in the constructor
   protected var registry:Dictionary = new Dictionary();
   protected var _eventBus:IeventDispatcher;
   public function registerResource(resourceName:String, resourceClass:Class):void {
      var bitmap:BitmapData = new resourceClass as BitmapData;
      if (resourceClass) {
          registry[resourceName] = bitmap;
      } else {
          trace('Class didn\'t make a BitmapData');
      }
   }
   public function getResource(resourceName:String):BitmapData {
      var resource:BitmapData = registry[resourceName];
      if (!resource) trace('there was no resource registered for', resourceName);
   }
   public function get eventBus():IEventDispatcher {
      return _eventBus;
   }
   public function set eventBus(value:IEventDispatcher):void {
      if (value != _eventBus){
         if (_eventBus) {
            _eventBus.removeEventListener(YourCustomEvent.GET_RESOURCE, provideResource);
         }
         _eventBus = value;
         if (_eventBus) {
            _eventBus.addEventListener(YourCustomEvent.GET_RESOURCE, provideResource);
         }
      }
   }
   protected function provideResource(e:YourCustomEvent):void {
      var client:IBitmapResourceClient = e.target as IBitmapResourceClient;
      if (client) {
         client.resource = getResource(e.resourceName);//your custom event has a resourceName property that you populated when you dispatched the event.
      }
   }
}

Note that I didn't provide the Interface or the custom event or an example implementation of the Interface due to the fact I am on my lunch break, but if anyone needs that to understand the code please post back and I'll fill that in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top