本帖最后由 韩松范 于 2013-3-12 02:34 编辑
在学习视频中,毕老师关于单例模式的饿汉式的代码结构如下:
class Single{
private Single(){}
private String name = "han";
private static Single single = new Single();
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public static Single getInstance()
{
return single;
}
}
我的问题是上段代码可不可以这样写
class Single{
private Single(){}
private String name = "han";
public static Single singleton = new Single();//把private权限改称,public ,这样在创建对象时可以Single s1 = Single.singleton
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
/*public static Single getInstance()//注视掉这个静态成员函数
{
return single;
}*/
}
如果想拿到该类的对象:
public static void main(String[] args)
{
Single s = Single.singleton;
System.out.println(s.getName());
Single s1 = Single.singleton;
s1.setName("hahahahah");
Single s3 = Single.singleton;
s3.setName("I'm s3");
System.out.println(s.getName());
}
打印结果为:han
I'm s3
所以这种方法貌似也可以,而且代码好像更简练,这样写可不可以?
|