开发者

Singleton Enforced Classes?

开发者 https://www.devze.com 2023-02-26 04:51 出处:网络
What\'s the purpose of using Singleton Enforced classes and does anyone have any exampl开发者_开发百科es of how to create/use them?

What's the purpose of using Singleton Enforced classes and does anyone have any exampl开发者_开发百科es of how to create/use them?

I was told I could do global variables (session) by using this idea, is it true?


The purpose of the Singleton Pattern is to make sure only a single instance of some object exists. It is usually used in flex to add Global State to a project. In other words, it allows you to do things like set and have access to global variables from anywhere in your application.

package {

  [Bindable]
  public final class AppGlobals {

    public static var _instance:AppGlobals;

    public function AppGlobals( enforcer:SingletonEnforcer ){
      if( enforcer == null ){
        throw new Error( "You can only have one active instance of AppGlobals.");
      }
    }

    public static function getInstance():AppGlobals {
      if( _instance == null ) _instance = new AppGlobals( new SingletonEnforcer );
      return _instance;
    }

  }

}

class SingletonEnforcer {}

To use this, you should instantiate your AppGlobals at the highest level of your application (main.mxml or whatever your top level is), by doing something like this:

private var _appGlobals:AppGlobals = AppGlobals.getInstance();

Then, anywhere in your application you can instantiate a copy of AppGlobals the same way, and have access to a global state of information.

To answer the second part of your question, yes, you can use this to setup global session variables in your application. Some people debate whether it is the best way to approach this (surely not ideal for every single situation), but I have found it useful.

Hope this helps!


Just keep in mind the following. Singleton shouldn't solve lack of application design and used as global entry point. The only valid usage of Sinltone is ensure if there is only one instance of particular class (see also Multiton to control number of instances).

So you should think twice or even more times before deciding to use Singleton. Should you restrict number of instances of particular class? What if there will be more than one single instance — does it break domain model or something?

Anyway do not use Singletons and statics for solving architectural problems to have global entry point. Using Singltones you can spend a lot of time in future refactoring your application.

0

精彩评论

暂无评论...
验证码 换一张
取 消