singleton模式的实现方法有很多种么?

03-03-17 hitdemo2002
除了板桥写的,我在developerwork上还看到了用静态方法和静态变量实现

Singleton模式,另外,theserverside上也有。

就拿板桥的

public class Singleton {

  private static Singleton instance = null;

  public static synchronized Singleton getInstance() {

  //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次     

  //使用时生成实例,提高了效率!

  if (instance==null)

    instance=new Singleton();

  return instance;   }

}

developerworks上类似的为

public class Singleton {

private static Singleton s;

private Singleton(){};

/**

* Class method to access the singleton instance of the class.

*/

public static Singleton getInstance() {

if (s == null)

s = new Singleton();

return s;

}

}

不知道现在究竟有多少种定义,是不是可以自己修改,哪几种是比较为大家公认的。

我还想知道Singleton的最原始的定义是什么,我知道自己还没有理解这个模式的本质,各位朋友帮帮忙吧,谢谢

banq
2003-03-17 21:24
常用的就是我说的第二种,其他一般可以不考虑。

wildfox
2003-03-20 10:06
除了上面提到的两种以外,我看到还有一种实现的方式,下面是原文(很抱歉,我觉得我翻译不好这一段,看它的原文会更加准确一些)

Static Classes as Singleton Patterns

There already is a kind of Singleton class in the standard Java class libraries:the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not

support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can’t create any instance of classes like Math, and can only call the static methods directly in the existing final class.

final class PrintSpooler

{

//a static class implementation of Singleton pattern

static public void print(String s)

{

System.out.println(s);

}

}

//==============================

public class staticPrint

{

public static void main(String argv[])

{

Printer.print("here it is");

}

}

One advantage of the final class approach is that you don’t have to wrap things in awkward try blocks. The disadvantage is that if you would like to drop the restrictions of Singleton status, this is easier to do in the exception style class structure. We’d have a lot of reprogramming to do to make the

static approach allow multiple instances.

richardluopeng
2003-03-21 09:00
我不认为Math是singleton模式,呵呵

manbaum
2003-03-21 17:08
同意 richardluopeng。

Singleton 是单实例,而 Math 是无实例。

猜你喜欢
5Go 1 2 3 4 ... 5 下一页