我正在实现我将用于检索应用程序中的一些背景的枚举类, 这个类的当前实现在这里:
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;
答案 0 :(得分:2)
您可以随时将画家定义为界面,并让您的枚举实现它。您将无法使用通用通配符,但只要这不是约束,您就可以按照您想要的方式在代码中引用画家:
interface Painter<T> {
// ...
}
public enum Painters implements Painter<Component> {
Background(getBackgroundPainter()),
InactiveBackground(getInactiveBackgroundPainter()),
DesktopBackground(getBackgroundPainter());
private Painter<Component> _painter;
// ...
}
Painter somePainter = Painters.Background;
你的枚举实际上会代替实际的画家实现。
答案 1 :(得分:2)
通常Enums
是为不可变常量保留的,你需要switch / case和constructors的语法糖。工厂模式更合适:
public class PainterFactory {
public static Painter<Component> getBackgroundPainter(){
...
}
public static Painter<Component> getInactiveBackgroundPainter(){
...
}
}