3

我正在实现枚举类,我将使用它来检索应用程序中的一些背景,这个类的当前实现在这里:

public enum Painters{

    /**
     * Available painters.
     */
    Background(getBackgroundPainter()),
    InactiveBackground(getInactiveBackgroundPainter()),
    DesktopBackground(getBackgroundPainter());

    /**
     * The background painter.
     */
    private Painter<Component> _painter;

    /**
     * Constructor will initialize the object.
     */
    Painters(Painter<Component> painter){
        _painter = painter;
    }

    /**
     * Will return a current painter.
     * @return instance of Painter<Component>
     */
    public Painter<Component> painter(){
        return _painter;
    }

    private static Painter<Component> getBackgroundPainter(){
        MattePainter mp = new MattePainter(Colors.White.alpha(1f));
        PinstripePainter pp = new PinstripePainter(Colors.Gray.alpha(0.2f),45d);
       return (new CompoundPainter<Component>(mp, pp)); 
    }

    private static Painter<Component> getInactiveBackgroundPainter(){
        MattePainter mp = new MattePainter(Colors.White.alpha(1f));
        GlossPainter gp = new GlossPainter(Colors.Gray.alpha(0.1f), GlossPainter.GlossPosition.BOTTOM);
        PinstripePainter pp = new PinstripePainter(Colors.Gray.alpha(0.2f), 45d);
        return (new CompoundPainter<Component>(mp, pp, gp));    
    }
}

我的问题是每次我尝试获取画家时都需要调用painter() 方法,但我更喜欢只写画家的类型。我认为如果我可以通过我的枚举来扩展 Painter,那么我可能会获得正确的功能,但它看起来在 java 中是不可能的。

public enum Painters extends Painter<Component>

你知道这个问题的任何解决方案吗???

目前我以这种方式使用它:

Painters.Background.painter();

但是我需要:

Painters.Background;
4

2 回答 2

2

您总是可以将您的画家定义为一个接口并让您的枚举实现它。您将无法使用通用通配符,但只要这不是约束,您也可以按照您想要的方式在代码中引用画家:

interface Painter<T> {
    // ...
}

public enum Painters implements Painter<Component> {
    Background(getBackgroundPainter()),
    InactiveBackground(getInactiveBackgroundPainter()),
    DesktopBackground(getBackgroundPainter());

    private Painter<Component> _painter;

    // ...
}

Painter somePainter = Painters.Background;

您的枚举将有效地代理实际的画家实现。

于 2012-04-29T11:57:48.507 回答
2

通常Enums保留用于不可变常量,您需要 switch/case 和构造函数的语法糖。工厂模式在这里更合适:

public class PainterFactory {
    public static Painter<Component> getBackgroundPainter(){
    ...
    }

    public static Painter<Component> getInactiveBackgroundPainter(){
    ...
    }
}
于 2012-04-29T11:58:58.710 回答