本帖最后由 阳光的嘉主角 于 2014-8-25 10:30 编辑
/**
* 单例 1
*
* @Description:饿汉
*/
class Single01 {
private Single01() {
}
private static Single01 single = new Single01();
public static Single01 getInstance() {
return single;
}
}
-------------------------------------------------------------------------------------
/**
* 单例 2
*
* @Description:懒汉
*/
class Single02 {
private Single02() {
}
private static Single02 single = null;
public static Single02 getInstance() {
if (single == null) {
single = new Single02();
}
return single;
}
}
-------------------------------------------------------------------------------------
/**
* 单例 3
*
* @Description:多线程下使用这个
*/
class Single03 {
private Single03() {
}
private static Single03 single = null;
public static Single03 getInstance() {
if (single == null) {
synchronized (Single03.class) {
if (single == null) {
single = new Single03();
}
}
}
return single;
}
}
-------------------------------------------------------------------------------------
/**
* 单例 4
*
* @Description:
*/
class Single04 {
private Single04() {
}
public static class Single04Holder {
public static final Single04 single = new Single04();
}
public static Single04 getInstance() {
return Single04Holder.single;
}
}
-------------------------------------------------------------------------------------
/**
* 单例 4
*
* @Description:
*/
enum Single05 {
// SINGLE();
// public static Single05 getInstance() {
// return Single05.SINGLE;
// }
SINGLE("帅哥", 20);
private String name;
private int age;
private Single05(String name, int age) {
this.name = name;
this.age = age;
}
public static Single05 getInstance() {
return Single05.SINGLE;
}
@Override
public String toString() {
return this.name + "<---age--->" + this.age;
}
}
public class Test {
public static void main(String[] args) {
Single05 single = Single05.getInstance();
System.out.println(single.toString());
}
}
帅哥<---age--->20 |
|