枚举:
单例&&多例
单例:
饿汉式单例:
class Singleton{
private static Singleton singletion = new singletion();
private Singleton(){}//构造方法私有化
public static Singleton getInstance(){
return singletion;
}
}
多例:
//多例:有限个对象
//首先构造方法私有化,再在类内部创建对象
class Color {
private String name;
//类内部创建对象
private static Color RED = new Color("Red");
private static Color YELLOW = new Color("Yellow");
private static Color BLUE = new Color("Blue");
private Color(String name) {//构造方法私有化
this.name = name;
}
public static Color getInstence(String colorName) {
switch (colorName) {
case "Red":
return RED;
case "Yellow":
return YELLOW;
case "Blue":
return BLUE;
default:
return null;
}
}
public String toString() {
return this.name;
}
}
public class Test {
public static void main(String[] args) {
Color red = Color.getInstence("Red");
Color blue = Color.getInstence("Blue");
System.out.println(red);
System.out.println(blue);
}
}
当对象有很多的时候,就必须在在类的内部new很多次,比较麻烦,所以在JDK1.5之后加了枚举;
枚举:enum
枚举实际上就是多例,Java中用enum来表示枚举,enum并不是一个新的结构,使用enum定义的枚举实际上默认
继承Enum枚举类,因此enum定义的枚举结构实际上就是一个多例类。
enum Color{//Color默认继承Enum类
RED,BLUE,YELLOW;
}
public class Test {
public static void main(String[] args) {
//枚举:
Color red = Color.RED;
System.out.println(red.ordinal()+"="+red.name());//ordinal()返回枚举编号+名称
}
}
Enum常用的三个方法:
ordinal():返回枚举对象下标,默认第一个对象编号为0;
name();返回枚举对象名称,默认与对象名称保持一致;
values();返回所有枚举对象。
枚举中支持定义其他结构,如构造方法、普通属性、普通方法等。
当枚举类中还包含有其他结构,枚举对象的定义必须放在首行。
枚举可以实现接口,枚举中的对象称为接口对象