3

I have been told that if I want to use an instance of my main class, I should do it with a constructor:

private <Main_Class_Name> plugin;
public <class_name>(<Main_Class_Name> plugin) {
    this.plugin = plugin;
}

Why is this better (or how does it differ) than just doing this?

private <Main_Class_Name> plugin = new <Main_Class_Name>();
spongebob
  • 8,370
  • 15
  • 50
  • 83
Leo H.
  • 53
  • 7
  • 2
    The first is a singleton. There's nothing "better" about it. Whoever that tells you that was misled. Now that aside, please take a __[tour]__ and learn what questions are expected of this site. – Unihedron Aug 15 '15 at 22:41
  • 1
    @Unihedron - I don't think the question is "out of scope" because OP wants to know the difference between the two statements. If he only wanted to know which was the better one, that would be another thing – bestprogrammerintheworld Aug 16 '15 at 12:39

3 Answers3

2

With Bukkit, you can create an instance of your main plugin (JavaPlugin) class with something like this:

public class MyPlugin extends JavaPlugin {
    public static MyPlugin instance;

    public void onEnable() {
        instance = this;
    }
}

Bukkit instantiates the plugin internally, but calls onEnable() on the instance of the plugin that is active in the server. This seems to be a commonly accepted method.

Keenan Thompson
  • 196
  • 1
  • 10
1

You should not use the second pattern because you should never instantiate your main class. That is, there should be only one instance of your main class, that one created by the plugin manager.

In my opinion, the first pattern requires too much work. Instead, implement the Singleton Pattern.

Anyway, JavaPlugin extends PluginBase which implements Plugin, so you could even do:

MainClass main = (MainClass)Bukkit.getServer().getPluginManager().getPlugin("Plugin_Name");
Community
  • 1
  • 1
spongebob
  • 8,370
  • 15
  • 50
  • 83
0

You can't use the second way for storing your main plugin instance, because it reconstructs your already constructed plugin, but the best way to store your main plugin instance is to save it to a public static field in onEnable method.

gyurix
  • 1,106
  • 9
  • 23