文章来源:黑马程序员,黑马论坛
|
枚举和单例设计模式的区别,黑马面试有的
public class Test11 {
public static void main(String[] args) {
//调用:字母对象 -- 1
System.out.println(Letter.A);
//输出:com.itheima.Letter@3020ad
//调用:字母枚举 -- 2
System.out.println(Letter2.A);
//输出:A
//调用:字母单例模式 -- 3
System.out.println(Letter3.getLetter3());
//输出:com.itheima.Letter3@60e128
/*
* 三者都可以调用,而[字母对象]和[字母枚举]是类似的
* 只不过[字母枚举 ]是类似简化版
* 如果字[字母枚举 ]里就一个A那么和[字母单例模式 ]就和类似了
*
* 具体了解可以参考以下几篇信息
* 1.http://cardyn.iteye.com/blog/904534
* 2.http://developer.51cto.com/art/201107/275031.htm
* 3.http://www.iteye.com/topic/1116193
*/
}
}
/**
* 字母对象 -- 1
*/
final class Letter{
//A 字母常量
public static final Letter A = new Letter();
//B 字母常量
public static final Letter B = new Letter();
//C 字母常量
public static final Letter C = new Letter();
/**
* 私有构造函数不可以外部实例化Letter
*/
private Letter(){}
}
/**
* 字母枚举 -- 2
*/
enum Letter2{
A,B,C
}
/**
* 字母单例模式 -- 3
*/
class Letter3{
//1.初始化一个a字母对象
private static Letter3 a = new Letter3();
/**
* 私有构造函数不可以外部实例化Letter
*/
private Letter3(){}
/**
* 调用获得字母对象,实现单例模式
* @return 字母对象
*/
public static Letter3 getLetter3(){
if (a == null){
a = new Letter3();
}
return a;
}
}