简体   繁体   中英

Java single instance means

"In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java".

I am not able to understand single instance means here.

For example :

 A  a = new A();

here what is a ? is it object or instance? if a is instance, does it mean that we can't do like below.

A b = new A() ie another instance 'b'

any diagrammatic example would help me.

Thanks

In your example, a is a reference to an instance of A , that got created by calling new A() .

You can very well do A b = new A(); , this means that now you have two instances of A around.

And an object means the same as an instance.

a there is a reference to the newly created object that new A() creates. That has nothing to do with the singleton pattern, though; that's always true.

In the singleton pattern, you would find a way of ensuring that new A() is only called once ever in the program. The typical way this is done is to make A 's constructor private, and create the instance from within A (which is thus the only class allowed to call the private constructor).

public class A {
    public static final A instance = new A();

    private A() {}

}

This approach does have a few edge cases, though: you can create extra instances through reflection, and through serialization if A is serializable. To really make a singleton, the best way in Java is to use enums:

public enum A {
    INSTANCE;
    // fields, methods etc go here
}

The JVM will ensure that only one A.INSTANCE exists in the process.

这里的'a'是指向创建的'new A()'引用。一旦创建了一个对象,您就无法在使用单例模式时创建其他对象。使用A b = new A()是错误的。

objects ARE instances. instances (= a case or particular example) of classes, which are some things written in programming language that define the semantics of objects themselves. When you use a singleton you define a class with a private constructor, this means that only instances of that class can call the constructor, so only instances of that class can create other instances of that class. the next step is to write a method that says. "do you want a reference to an instance of this object? well, if anyone asked this to me before, i'll create it and then i'll give it to you, or rather i give to you an instance already created".

So now you are asking "wait, if i need an instance of this class to get an instance of this class, how can i get an instance of this class without an instance of this class??!?". therese a simple answer to a complicated question: use static methods and fields

static code does not belong to any instance of the class, static variables and static method code are stored in other zones of address space, so you can use it before you have an instance of the singleton class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM