关于java:什么是单身,用简单的英语?

What is a singleton, in plain English?

我已经在谷歌上搜索了大约个小时,但我仍然不清楚单件是什么。有没有人能让我更清楚一点,或者发布一个代码示例?

我只知道,如果你只能有一个给定类的实例。但是你就不能用一个静态类来实现吗??

事先谢谢!


简单的纯英语版本是singleton类,它是一个只有一个实例的类。

But can't you just then use a static class for that?

不,这不是Java中的"静态"类。在Java中,"静态"类可以有多个实例,就像任何其他类一样。

static关键字用于(类)表示嵌套类的实例没有绑定到封闭类的特定实例。这意味着嵌套类中的表达式不能引用封闭类中声明的实例变量。

在Java 1.5之前(AKA Java 5),在爪哇中不支持单体设计模式。您只是在纯Java中实现它们;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    /** There is only one singer and he knows only one song */
    public class Singer {
        private static Singer theSinger = new Singer();
        private String song ="I'm just a singer";

        private Singer() {
            /* to prevent instantiation */
        }

        public static Singer getSinger() {
            return theSinger;
        }

        public String getSong() {
            return song;
        }
    }

Java 1.5引入了EDCOX1 1种类型,可用于实现单例等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    /** There are two Singers ... no more and no less */
    public enum Singer {
        DUANE("This is my song"),
        RUPERT("I am a singing bear");

        private String song;

        Singer(String song) {
            this.song = song;
        }

        public String getSong() {
            return song;
        }
    }


singleton是一个带有私有构造函数的类,您只能获取它的一个实例。为了进一步解释为什么采用这种编码方式,我建议您阅读本书中有关单件的章节。

http://www.wowbook.com/book/head-first-design-patterns网站/

第五章是关于单子的


The singleton pattern is a design pattern that restricts the
instantiation of a class to one object.

Note the distinction between a simple static instance of a class and a
singleton: although a singleton can be implemented as a static
instance, it can also be lazily constructed, requiring no memory or
resources until needed. Another notable difference is that static
member classes cannot implement an interface, unless that interface is
simply a marker. So if the class has to realize a contract expressed
by an interface, it really has to be a singleton.

全部来自维基百科