枚举实现的单例模式

来源:互联网 发布:php strrops 编辑:程序博客网 时间:2024/05/16 08:13

前段时间在看单例模式,里面提到了用枚举来实现单例比较好:http://blog.csdn.net/beyond0525/article/details/22794221

可是当时看不懂枚举是如何实现的。

今天又看到一个枚举的源码,也是看不懂,于是找了一些介绍枚举的文章,大概了解了:http://blog.csdn.net/veryitman/article/details/7945020,http://blog.csdn.net/lindir/article/details/8331996

枚举:

1. 一般用的枚举

enum Student {<span style="white-space:pre"></span>LiLei,LiLy,HanMeiMei;}
一般理解,LiLei这些每一个都是一个整型,0,1,2,依次加1

2. 较为复杂的枚举

enum Student {// 枚举对象LiLei(11, 1), LiLy(10, 2), HanMeiMei(12, 3);// 枚举的构造函数Student(int age, int score) {this.age = age;this.score = score;}// 成员变量int age;int score;}
LiLei就相当于一个Student的对象,包含两个成员变量age和score,并且在枚举Student里面已经初始化了

枚举实际是一个类:

Public abstract class Enum<E extends Enum<E>> implements Serializable,Comparable <E>    {      ...  }

理解了这个,就理解了枚举实现的单例
单例:

附上网友的一段代码:

/**  * @function:单例模式枚举实现  * @author xuzhaohu  *   */  public enum SingletonEnum {      /**      * 1.从Java1.5开始支持;      * 2.无偿提供序列化机制;      * 3.绝对防止多次实例化,即使在面对复杂的序列化或者反射攻击的时候;      */        instance;        private String others;        SingletonEnum() {        }        public void method() {          System.out.println("SingletonEnum");      }        public String getOthers() {          return others;      }        public void setOthers(String others) {          this.others = others;      }  } 

调用:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. SingletonEnum.instance.method();  











0 0
原创粉丝点击