刚学枚举类型是总觉的枚举类型似乎多此一举,一直在想枚举类型有什么意义。
看到网络上很多枚举类型的例子,觉的很适合颜色调配这个案例,感觉枚举最大的意义是可以像对象一样操作。
自己结合枚举的优点写了一个实用的例子,代码会优雅和精简了许多,供参考。
package utils;
public enum LxzColor{
Red(255,0,0),
Green(0,255,0),
Blue(0,0,255),
Black("#000000"),
Purple("#6F00D2"),
Yello("#F9F900"),
White("#FFFFFF");
//模式RGB色,HTML色
enum ColorAdapter{
All{
public String toString(LxzColor clr) {
return "["+"htmlcode="+clr.htmlcode+" RGB={"+clr.r+","+clr.g+","+clr.b+","+"}"+"]";
}
},
RGB{
public String toString(LxzColor clr) {
return "["+clr.r+","+clr.g+","+clr.b+"]";
}
},
HTML{
public String toString(LxzColor clr) {
return clr.htmlcode;
}
};
public String toString(LxzColor clr) {
return "["+"htmlcode="+clr.htmlcode+" RGB={"+clr.r+","+clr.g+","+clr.b+","+"}"+"]";
}
}
String htmlcode;
int r;
int g;
int b;
private LxzColor(String htmlcolor)
{
htmlcode=htmlcolor;
r=Integer.valueOf(""+htmlcolor.charAt(1)+htmlcolor.charAt(2),16);
g=Integer.valueOf(""+htmlcolor.charAt(3)+htmlcolor.charAt(4),16);
b=Integer.valueOf(""+htmlcolor.charAt(5)+htmlcolor.charAt(6),16);
}
private LxzColor(int r,int g,int b)
{
this.r=r;
this.g=g;
this.b=b;
String $r=String.valueOf(Integer.toHexString(r));
$r=$r.length()==1?0+$r:$r;
String $g=String.valueOf(Integer.toHexString(g));
$g=$g.length()==1?0+$g:$g;
String $b=String.valueOf(Integer.toHexString(b));
$b=$b.length()==1?0+$b:$b;
htmlcode=("#"+$r.toUpperCase()+$g.toUpperCase()+$b.toUpperCase());
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
public String toString(ColorAdapter type) {
// TODO Auto-generated method stub
return type.toString(this);
}
}
package utils;
import utils.LxzColor.ColorAdapter;
public class dotest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(LxzColor.values());
//打印
System.out.println(LxzColor.Black);
System.out.println(LxzColor.valueOf("Red"));
System.out.println(LxzColor.valueOf(LxzColor.Blue.toString()));
System.out.println("----------------------");
for(int i=0;i<LxzColor.values().length;i++)
{
System.out.println("序列数"+LxzColor.values()[i].ordinal());
System.out.println(LxzColor.values()[i]);
System.out.println(LxzColor.values()[i].toString(ColorAdapter.RGB));
System.out.println(LxzColor.values()[i].toString(ColorAdapter.HTML));
System.out.println(LxzColor.values()[i].toString());
System.out.println("----------------------");
}
}
}
输出结果
[Lutils.LxzColor;@61de33
Black
Red
Blue
----------------------
序列数0
Red
[255,0,0]
#ff0000
Red
----------------------
序列数1
Green
[0,255,0]
#00ff00
Green
----------------------
序列数2
Blue
[0,0,255]
#0000ff
Blue
----------------------
序列数3
Black
[0,0,0]
#000000
Black
----------------------
序列数4
Purple
[111,0,210]
#6F00D2
Purple
----------------------
序列数5
Yello
[249,249,0]
#F9F900
Yello
----------------------
序列数6
White
[255,255,255]
#FFFFFF
White
----------------------