Singleton Java实现

问题描述 投票:-1回答:3

我已经在Internet上为单例找到了此代码,但我想知道如何在我的Java代码中实现它?

static FKPlugin instance;

onEnable:
    instance = this;
onDisable:
    instance = null;

public static FKPlugin getInstance():
    return instance;
java singleton bukkit
3个回答
0
投票

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

枚举类别:

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

通话类:

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());
    }
}

0
投票

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

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

    private Singleton() {}

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

0
投票

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

单例模式背后的思想是基本上[[确保一个类只有一个实例,同时提供对此实例的全局访问点

并且要实现这一点,基本方法是

将构造函数保持私有,同时公开用于获取该类的单例实例的公共方法。] >>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中使用单例模式的其他方式的更多信息。
© www.soinside.com 2019 - 2024. All rights reserved.