The main idea behind implementing plugins in any object oriented language, is to define a set of common interfaces that the plugin and related classes must implement, and then load and instantiate them via reflection...
You can use abstract factory pattern so that any objects needed by the plugin can be instantiated...
Let's say that your plugin architecture has only 3 interfaces and each plugin must provide classes that implement those interfaces, then your plugin architecture could be like this:
public interface PluginInterfaceA {
//Define API here
};
public interface PluginInterfaceB {
// Define API here
};
public interface PluginInterfaceC {
// Define API here
};
public interface PluginFactory {
/**
* Creates plugin A object.
*/
PluginInterfaceA createPluginA();
/**
* Creates plugin B object.
*/
PluginInterfaceB createPluginB();
/**
* Creates plugin C object.
*/
PluginInterfaceC createPluginC();
};
And then let the plugins to define in an XML file or properties file the class name of the plugin factory for the plugin:
For instance let's say your plugin defines:
package com.my.plugin;
public class PluginAImpl implements PluginInterfaceA {
// Code for the class
};
public class PluginBImpl implements PluginInterfaceB {
// Code for the class
};
public class PluginCImpl implements PluginInterfaceC {
// Code for the class
};
public class PluginFactoryImpl implements PluginFactory {
public PluginInterfaceA createPluginA() {
return new PluginAImpl();
}
public PluginInterfaceB createPluginB() {
return new PluginAImpl();
}
public PluginInterfaceC createPluginC() {
return new PluginAImpl();
}
};
And then define in the properties file
// File plugin.properties provided in the plugin.jar of the plugin
plugin.factory.class = com.my.plugin.PluginFactoryImpl;
In your application can do
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("plugin.properties"));
String factoryClass = properties.get("plugin.factory.class");
PluginFactory factory = Class.forName(factoryClass);
PluginInterfaceA interfaceA = factory.createPluginA();
PluginInterfaceB interfaceB = factory.createPluginB();
PluginInterfaceC interfaceC = factory.createPluginC();
// Here invoke created classes as you like.
Thanks
Pablo