Is there any way to prevent the creation of only one object?

Asked 2 years ago, Updated 2 years ago, 32 views

Is there any way to prevent the creation of only one object? For example, there's only one person in the world like me. so If you instantiate me, I want to prevent you from objectifying more than one object because there's only one person, but what can I do?

java singleton

2022-09-22 13:12

1 Answers

You can use the single tone pattern. A single tone is a class in which only one instance is created. The implementation method enables the constructor to be private and provides members as public static to access the instance. For example,

public class Elvis{
    public static final Elvis INSTANCE = new Elvis();
    private Elvis(){....}

    public void leaveTheBuilding(){....}
}

In this way, the private constructor is called only once to initialize the public static final field, Elvis.INSTANCE. Since there is no public or protected constructor, we guarantee a world where only one Elvis exists.

The second way is to have the static factory method as a public member.

public class Elvis{
    private static final Elvis INSTANCE = new Elvis();
    private Elvis(){....}
    public static Elvis getInstance(){ return INSTANCE;}

    public void leaveTheBuilding(){....}
}

Elvis.getInstance always returns the same object, no matter how many times it is called this way, and another Elvis is never created.


2022-09-22 13:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.