大侠们帮忙瞧瞧! 关键字:设计模式 singleton

shmily_nnx 2003-11-20 03:30:28
做一个singleton,发现有些东西比较怪。拿出来一起看看。
下面的代码没什么问题
protected static myclass instance;

public static Instance()
{
if(instance==null)
return new myclass();
else
return instance;
}

等价于下面的代码

protected static myclass instance=null;

public static Instance()
{
if(instance!=null)
return instance;
else
return new myclass;
}

但是以下程序不行,Exception为instance未实例化

protected static myclass instance;

public static Instance()
{
if(instance!=null)
return instance;
else
return new myclass;
}
...全文
17 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
shmily_nnx 2003-11-20
  • 打赏
  • 举报
回复
天哪,自取欺辱啊!!!
if(instance==null)
return new myclass();
else
return instance;
第一个return的并不是instance变量啊。妈妈的,我的搞什么啊。大家就当没提过这个问题。
嘿嘿
shmily_nnx 2003-11-20
  • 打赏
  • 举报
回复
嘿嘿,不好意思,应该是
public static myclass Instance()
{
if(instance==null)
return new myclass();
else
return instance;
}
漏掉了个类型,其它两个也一样。我郁闷的是前两个可以没问题,为什么第三个有问题?
class怎么初始化静态成员?难道protected static myclass instance;初始化instance的时候除了myclass类型和null之外还有第三种?初始化instance难道不是null?
三段代码中的if else的区别足以改变程序的结果??
期待答案ing

MH2o 2003-11-20
  • 打赏
  • 举报
回复
因为上面的代码比较少也比较好懂注释就不写了(懒!!!)
:-)
MH2o 2003-11-20
  • 打赏
  • 举报
回复
我给一个关于singleton模式的一个测试用例和实现(所有的源码都是Java写的应该能看懂)
测试用例:
import junit.framework.*;
import java.lang.reflect.Constructor;

public class TestSimpleSingleton extends TestCase
{
public TestSimpleSingleton(String name)
{
super(name);
}

public void testCreateSingleton()
{
Singleton s = Singleton.Instance();
Singleton s2 = Singleton.Instance();
assertSame(s,s2);
}

public void testNoPublicConstructors() throws Exception
{
Class singleton = Class.forName("Singleton");
constructor[] constructors = Singleton.getConstructors();
assertEquals("Singleton has public constructors."0,constructors.length);
}
}


具体的Singleton 的实现:
public class Singleton
{
private static Singleton theInstance = null;
private Singleton();

public static Singleton Instance()
{
if (theInstance == null)
theInstance = new Singleton();
return theInstance;
}
}
大概就这样子吧!最近偶也在研究关于设计模式的问题,有机会大家一起研究研究。
我的Msn:mh2o88@hotmail.com
ludingping 2003-11-20
  • 打赏
  • 举报
回复
public static Instance()
{
if(instance!=null)
return instance;
else
return new myclass;
}

中没有返回类型。
你的问题很怪。我也想不出来。
brightheroes 2003-11-20
  • 打赏
  • 举报
回复

protected static myclass instance=null;
MH2o 2003-11-20
  • 打赏
  • 举报
回复
protected static myclass instance;和protected static myclass instance=null;???

110,556

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧