问题
I have an AIR application that uses Singletons to manage global state throughout the application. Works great for what it does (manages a network appliance). But now the client wants to spawn multiple application instances from the first instance so they can manage multiple hardware devices at the same time ... kind of like a dashboard but lots bigger.
As you can guess, I coded myself into a corner with the singletons so if I refactor the application to have a bootstrap class that launches the application logic with a button, let's say, that spawns another window that contains the same application logic, then the singletons are shared across both app windows whereas I would have liked two separate instances.
Is there a way to use singletons ( or something else ) to keep global state but create multiple instances in one application where each instance needs it's own state manager?
回答1:
There are several different options:
- Load each application instance into it's own
ApplicationDomain
- Use one of the dependency injection frameworks where you don't get the singleton - instead of this it's value is assigned to your class property in runtime. All the stuff is managed by the metadata. It would require some code changes.
- Refactor your code so that each class instance would know it's context. This can be implementing by adding a constructor parameter or
setContext(value:Context)
function.Context
instance will contain links to all your ex-singletons. - Go up the display list until you find some class instance that can provide you the links to ex-singletons. Make sure that each non-display-list object has a link to display list object to get singletons too.
来源:https://stackoverflow.com/questions/8511751/air-application-written-using-singletons-needs-to-spawn-multiple-instances-of-ap