代码之家  ›  专栏  ›  技术社区  ›  Eric Belair

在flex应用程序中,我应该在哪里存储重用的静态字符串常量?

  •  2
  • Eric Belair  · 技术社区  · 16 年前

    我有两个cairngorm mvc flex应用程序(同一个应用程序的完整版本和精简版本)共享许多类。我已经将这些类放入了一个作为SWC编译的flex库项目中。两个应用程序都使用一些静态字符串常量。现在,我将这些存储在ModelLocator中:

    package model
    {
        [Bindable]
        public class ModelLocator
        {
            public static var __instance:ModelLocator = null;
    
            public static const SUCCESS:String = "success";
    
            public static const FAILURE:String = "failure";
    
            public static const RUNNING:String = "running";
    
            ...
        }
    }
    

    这似乎不是存储这些常量的最佳位置,尤其是现在两个应用程序都使用了这些常量,我已经设置了每个应用程序都有自己的ModelLocator类。另外,这不是ModelLocator类的用途。

    在我的共享库中存储这些常量的好方法是什么?

    我应该创建一个这样的类吗?:

    package
    {
        [Bindable]
        public class Constants
        {
            public static const SUCCESS:String = "success";
    
            public static const FAILURE:String = "failure";
    
            public static const RUNNING:String = "running";
        }
    }
    

    然后像这样引用它:

    if (value == Constant.SUCCESS)
        ...
    
    1 回复  |  直到 16 年前
        1
  •  13
  •   Herms    16 年前

    我想说,按逻辑意义组织常量,而不是用一个常量类。

    假设您有3个显示为某种任务状态,还有一些用于文件访问的错误代码(只需在此处填写内容):

    public class TaskStates {
      public static const SUCCESS:String = "success";
      public static const FAILURE:String = "failure";
      public static const RUNNING:String = "running";
    }
    
    public class FileErrors  {
      public static const FILE_NOT_FOUND:String = "filenotfound";
      public static const INVALID_FORMAT:String = "invalidformat";
      public static const READ_ONLY:String = "readonly";
    }
    

    我发现这样可以更容易地记录某个事物的期望值。您不必说“返回成功、失败、运行……”,只需说“返回taskstate.*值之一”。

    您可以将所有这些都放在一个常量包中,也可以让常量类与使用它们的类住在同一个包中。

    推荐文章