public enum SingleTon{ // 但是用dos 编译为什么去掉了 public 就编译通过了呢?
singleTon;
private SingleTon(){}
public static SingleTon getInstance(){
return singleTon;
}
}
public class SingleTonTest{
public static void main(String[] args){
SingleTon s1=SingleTon.getInstance(); //是否可以写成SingleTon.singleTon;?
SingleTon s2=SingleTon.getInstance();
System.out.println(s1 == s2);
// System.out.println(s1.getInstance() == s2.getInstance()); 如上所说,再来调用方法呢?注意这个时候getInstance ()没有static 修饰,但是这么写好像过于繁琐
}
}
也可以直接写成下面的形式:
public enum SingleTon{
singleTon;
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
this.age=age;
}
}
public SingleTonDemo{
public static void main(String[] args){
SingleTon s1 = SingleTon.singleTon;
SingleTon s2 = SingleTon.singleTon;
System.out.println(s1 == s2);
s1.setAge(25);
System.out.println(s2.getAge()); // 25
}
}
正如示例中写的问题一样,问题也就清晰,能够搞定了。这样的话,好像比较简单
传统的单例定义模式:饿汉式
单例的目的:就是要对外提供一个对象,枚举时,singleTon 相当于普通类中的 private static Singleton singleTon = new SingleTon();中的singleTon,不过好像有点麻烦
public class SingleTon{
private SingleTon(){}
private static final SingleTon singleTon = new SingleTon();
public static SingleTon getInstance(){
return singleTon;
}
}
|