多例设计模式:
特色: 构造方法私有化,类内部提供多个实例化对象,后面经过static方法返回java
class Color { private static final Color RED = new Color("RED"); private static final Color GREEN = new Color("GREEN"); private static final Color BLUE = new Color("BLUE"); private String title; private Color(String title) { this.title = title; } private static Color getInstance(int ch) { switch (ch) { case 0 : return RED; case 1 : return GREEN; case 2 : return BLUE; default: return null; } } public String toString() { return this.title; } public class TestDemo { public static void main(String[] args) { System.out.println(Color.getInstance(0)); } } }
上面的代码是在JDK1.5 以前的作法,目的在于限制本类实例化对象的产生个数。可是JDK1.5以后用枚举进行代替,能够大大简化面试
enum Color { RED, GREEN, BLUE; } public class TestDemo { public static void main(String[] args) { System.out.println(Color.RED); } }
实际上枚举就是一种高级的多例设计模式。设计模式
enum是对一种类型的包装,本质是一个class 定义的类继承了java.lang.Enum
父类
public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable
数组
Enum类中的方法
构造方法: protectd Enum(String name, int ordinal);
this
取得枚举名字: public final String name()
取得枚举序号: public final int ordinal()
取得全部的枚举数据: values() 返回的是枚举的对象数组设计
// values() 方法的使用 public class TestDemo { public static void main(String[] args) { for (Color temp : Color.values()) { //values能够看作枚举和多例的区别 System.out.println(temp.ordinal() + " = " + temp.name()); //返回: 0 = RED 1 = GREEN 2 = BLUE } } }
面试题:解释enum 和 Enum的区别
enum 是一个关键字, 使用enum定义的枚举类本质上就至关于一个类继承了Enum这个抽象类code
多例设计是在一个类当中产生的,在类中能够定义更多的属性或方法对象
枚举提供更强大的设计方案 + 属性 + 方法 + 接口 在枚举中定义更多的结构继承
enum Color { RED("红色"), GREEN("绿色"), BLUE("蓝色"); // 若是定义有许多内容,枚举对象必须在第一行 private String title; private Color(String title) { // 构造方法必定不能用public, 多例设计的原则 this.title = title; } public String toString() { return this.title; } } public class TestDemo { public static void main(String[] args) { System.out.println(Color.RED); } }