开发者

Enum Multiton Pattern

开发者 https://www.devze.com 2023-02-13 19:15 出处:网络
Is a good idea to use enum\'s for Multiton patte开发者_如何学Gorn if the number of instances for Multitonis fixed at compile-time.I have seen the Enum Sigleton pattern,so i was just wondering if the s

Is a good idea to use enum's for Multiton patte开发者_如何学Gorn if the number of instances for Multiton is fixed at compile-time.I have seen the Enum Sigleton pattern,so i was just wondering if the similar can be done for Multiton's too ?


The description of the pattern you linked to doesn't have a fixed set of keys, so I'm not sure you could call it a Multiton if you have a fixed set of keys. But if we accept it, then yes, enum instances each are a singleton.

Remember that enums are objects : they can have state and methods.


In C# I've often used a pattern I call "smart enums" or "heavy enums", where I want something you can think of as (a) an enum whose values are objects (like Java allows), or (b) a class in which all the possible instances are defined at compile-time (which is how I implement it). For example, I've modeled the concept of musical mode like this:

public class MusicalMode
{
    public readonly String Name;
    public readonly int Number;   // starting reference note: 1=C, 2=D, etc.
    public readonly int[] Intervals;  // 1 = half step, 2 = whole step

    public string ToString () 
    { /* implementation omitted */ }  

    public static MusicalMode FromString (String s) 
    { /* implementation omitted */ }

    // these are the only instances that can ever exist
    public static readonly Mode Ionian     = new Mode(1, "Ionian");
    public static readonly Mode Dorian     = new Mode(2, "Dorian");
    public static readonly Mode Phrygian   = new Mode(3, "Phrygian");
    public static readonly Mode Lydian     = new Mode(4, "Lydian");
    public static readonly Mode Mixolydian = new Mode(5, "Mixolydian");
    public static readonly Mode Aeolian    = new Mode(6, "Aeolian");
    public static readonly Mode Locrian    = new Mode(7, "Locrian");

    private Mode (int num, String name)
    { /* implementation omitted */ }
}

When I first learned about the Multiton pattern, I thought "Oh, I've done that!", thinking of my smart/heavy enums. But now I'm not sure, based on JB Nizet's remark about whether the set of keys is fixed (as it is in my example).

Is my MusicalMode an example of a Multiton? If not, is there a well-established name for that pattern?


I think Dependency Injection tools like Guice or Spring Framework IoC is more preferable for this purpose now as you can manage scope, state and other interesting stuff.

0

精彩评论

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