单例 java 实现

Singleton java implementation

我不太理解我的 bukkit 插件中单例的概念。在我的插件中,我需要获取插件数据文件夹并更改 json 文件。我必须使用函数 this.getDataFolder().getAbsolutePath(); 但它不能在我的插件中使用,因为我使用静态函数。 我已经尝试过这样做:

@Override
public void onEnable() {
   File file = getFile();
}

public static getFile() {
   return this.getDataFolder().getAbsolutePath();
}

我使用静态函数,因为我的插件分为多个文件。

在 java 中实现单例模式的最佳方法是通过 ENUMS,您可以参考下面的代码:

枚举Class:

public enum SingletonEnum {
    INSTANCE;
    int value;
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
}

呼叫 class:

public class EnumDemo {
    public static void main(String[] args) {
        SingletonEnum singleton = SingletonEnum.INSTANCE;
        System.out.println(singleton.getValue());
        singleton.setValue(2);
        System.out.println(singleton.getValue());
    }
}

这是单例模式,可以搜索google。例如:

public final class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

下面是在java中使用单例模式的演示。它使用 Lazy Initialization,因此单例实例仅在调用时分配。

单例模式背后的思想基本上是确保一个class只有一个实例,同时为该实例提供一个全局访问点.

为了实现这一点,基本方法是 将构造函数保持私有,同时公开一个 public 方法来获取 class.

import java.util.*;
import java.lang.*;
import java.io.*;

class Box
{
    private int x,y,z;
    private static Box instance;

    private Box(){
        x=y=z=2;
    }

    public static Box getSingleTonInsnace(){
        if(instance == null){
            instance = new Box();
        }
        return instance;
    }
    public String toString(){
        return String.format("Box with volume = %d", x*y*z);
    }

}

public class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Box box = Box.getSingleTonInsnace();
        System.out.println(box);
    }
}

您还可以查看此 link 以了解有关在 java 中使用单例模式的其他方法的更多信息。