how to create singleton classes for multiple uses
and how to connect to jsp with that singleton class
I'm not sure why yould want to connect to a singleton from you JSP directly. If you want to access utility function I'd go with a JSTL function:
<function>
<name>decodeBase64</name>
<function-class>nl.wikiwijs.web.portal.Base64Util</function-class>
<function-signature>java.lang.String stringDecodeBase64(java.lang.String)</function-signature>
</function>
Where 'function-signature' points to a static method in the 'function-class' class. The above should be in a TLD, after which I can be used like this:
${mynamespace:decodeBase64("my value")}
If the singleton is going to be used to retrieve data or expose business logic I'd move it back into a controller/action/component depending on your architecture.
for connecting to jsp, you would use p3t0r's answer.
for singleton, you would use a lazy private static class singleton which guarentees thread safety*:
public class SingletonClass {
private static class LazySingletonInitializer {
static SingletonClass instance = new SingletonClass();
}
private SingletonClass(){}
public SingletonClass getInstance() {
return LazySingletonInitializer.instance;
}
}
(*) because static members of a class are guarenteed by the jvm to be initialized by only one thread.
If you plan to use the Singleton pattern within a Java EE application, have a look at this article. It will provide some important insights as well as links for further research.
As stated by p3t0r, using services directly from within your JSP is not architecturally sound. Try seperating concerns by using some kind of MVC framework (e.g. Spring Web MVC, which, in conjunction with the Spring DI container, frees you from using your own singleton implementations, too).
Basic singleton design pattern has few special characteristics:
No constructor: make sure that the default constructor is private
Create a static function that calls the private constructor(s) if the object is not instantiated already
Have a static instance variable that is the type of its own class.
One example of a simple singleton class implementation is:
public class SingletonClass {
private static SingletonInstance si;
private SingletonClass() {
}
public static synchronized SingletonClass getSingletonInstace() {
if (si == null)
return new SingletonClass();
return si;
}
}
Related
This may be a bit difficult to describe, so I'll try to give a concrete example of what I'm trying to do.
Suppose we have a Facade interface and class (in Java), like this:
interface FacadeInterface<T> {
void method(String from, String via);
}
class Facade<T> implements FacadeInterface<T> {
private Class<T> mClazz;
public Facade(Class<T> clazz) {
mClazz = clazz;
}
#Override
public void method(String from, String via) {
System.out.println("Method called from " + from + " via " + via);
}
}
In my applications, I need to have multiple singletons which hold an instance of the facade. The real facade has additional setup/config parameters but those are irrelevant here.
Before I started using kotlin, I would have a class which holds a static instance of the facade (not really a singleton, but in my case, it served a similar purpose) which proxied the calls to the facade, like this:
public class Singleton {
private static final FacadeInterface<String> sFacade = new Facade<>(String.class);
private Singleton() {
}
public static void method(String from, String via) {
sFacade.method(from, via);
}
}
Now, with Kotlin we have class delegates which allow me to write something like this:
object SingletonKt : FacadeInterface<String> by Facade(String::class.java)
This is great - no more boilerplate and I can call SingletonKt from Kotlin classes the same way I called the java Singleton:
Singleton.method("Kotlin", "Singleton")
SingletonKt.method("Kotlin", "SingletonKt")
But, a slight problem arises when I use SingletonKt from Java. Then I have to specify INSTANCE:
Singleton.method("Java", "Singleton");
SingletonKt.INSTANCE.method("Java", "SingletonKt");
I am aware of the #JvmStatic annotation, but the only place I can put it in the SingletonKt file without causing compile errors is right before FacadeInterface and it doesn't seem to do the trick.
Is there a way to set up this class delegate so that I can call it from Java as if it were a static method, without introducing the boilerplate of creating proxy methods for SingletonKt (which would defeat the purpose of the class delegate)?
It's sadly not possilble!
The Kotlin Delegation is a nice way to reduce boilerplate code. But it comes with the inability to actually access the delegate within the class body.
The second issue you're facing regarding #JvmStatic is actually more drastic to your cause than the first and also applies to you when implementing the delegation manually:
Override members cannot be '#JvmStatic' in object
So instead of exposing the method() through the INSTANCE only, you could delegate it to a staticMethod() on the object. This still differs from your intent, but comes close to it.
object SingletonKt : FacadeInterface<String> by Facade(String::class.java)
#JvmStatic fun staticMethod(from: String, via: String) = method(from, to)
}
I don't know if it is possible to have delegated methods as static methods inside an object in Kotlin.
However, as you are interested in creating singletons that proxy a class, you could use package-level constants in Kotlin:
val SingletonKt : FacadeInterface<String> = Facade(String::class.java)
Now, you can call SingletonKt.method just like you would in Java. Note that you need to use a static import in Java to be able to use the SingletonKt constant.
This also allows you to use features like lazy to only create the singleton (or, in this case, instance) when you need it.
I recently got a book from amazon.in named java design patterns. Now i am reading factory design pattern. I could not get what is loose coupling please help me. explain me in an easy way. give me an example.
public interface Iscan {
void scan();
}
public EyeScannerClass implements Iscan{
void scan(){
System.out.println("Some Person's eye scanned...")
}
public BarcodeScannerClass implements Iscan{
System.out.println("A produc's barcode from supermarket scanned...")
}
public ScannerFactory{
public static Iscan createScanner(){
//here you can choose which scanner to create by the help of polymorphism because different scanner classes implementing same scanner interface
}
}
public SomeBusinessLogicClass {
public void someMethod(){
//if the scanner impl changes you do not need to change your business logic. all change must be done in factory and the other users of that factory is not affected.
Iscan scanner=ScannerFactory.createScanner();
}
}
I tried to explain why it is useful using factory design pattern above. we have an interface and two implementers of that interface and a factory class which is creating scanners and a client using that factory. if sth changes at the scanner impl the client do not need to change anything. With this approach we provide loose coupling.
Consider the below code(1)
Class Vehicle{
int modelYear=2010;
Engine engine=new Engine(); //Engine object
}
Now consider this(2)
Class Vehicle{
int modelYear;
Engine engine;
Vehicle(int modelYear,Engine engine)
{
this.modelYear=modelYear;
this.engine=engine;
}
In case 1 The Vehicle class is depending on the Engine class to create Engine object means more dependency i.e tight coupling
In case 2 we are creating Engine object else where(Container) and passing the object via constructor or setter method. means less dependency i.e loose coupling.
Factory Design Pattern talks about the same thing,to decrease the dependency between 2 classes create objects elsewhere and pass them via constructors or setter methods.
Whole spring framework is based on this,i.e loose coupling where IOC container creates the objects when needed, and injects them to the respective destination(Dependency Injection)
So I have a class like so:
public class HBaseUtil {
private final String fileName = "hbase.properties";
private Configuration config;
private HBaseUtil() {
try {
config = new PropertiesConfiguration(fileName);
} catch (ConfigurationException e) {
// some exception handling logging
}
}
// now some getters pulling data out of the config object
public static String getProperty(String fieldKeyName) {...}
public static String getColumnFamily(String fieldName) {...}
// ... some more getters
// NO setters (thus making this a read-only class)
}
Thus, basically I have for myself a Singleton class, that the very first time that it is put to use, sets up a configuration object, and then simply keeps listening for get calls. There are a number of problems with this class:
Unit testing the static methods within class HBaseUtil becomes difficult because of a tight-knit coupling between the Singleton and the configurations file.
What I really want is me being able to supply the filename/filename+path to the class so that it can go in there, read the configuration properties from that file and offer them to incoming read requests. One important note here though: I need this flexibility in specifying the properties file ONLY ONCE per JVM launch. So I certainly don't need to maintain state.
Here is what I was able to come up with:
Instead of a Singleton, I have a normal class with all static methods and no explicit constructor defined.
public class HBaseUtil {
// directly start with getters
public static String getProperty(Configuration config, String fieldKeyName) {...}
public static String getColumnFamily(Configuration config, String fieldKeyName) {...}
// ...and so on
}
And then, instead of using the class in my other code like such:
HBaseUtil.getProperty(String fieldKeyName)
I'd use it like so:
Configuration externalConfig = new PropertiesConfiguration("my-custom-hbase.properties");
HbaseUtil.getProperty(externalConfig, fieldKeyName)
My questions:
Am I even thinking in the right direction? My requirement is to have the flexibility in the class only ONCE per JVM. All that needs to be configurable in my project for this, is the location/contents of the HBase .properties file. I was thinking having a Singleton is overkill for this requirement.
What other better approaches are there for my requirement (stated in above point)?
Thanks!
Note: I've read this StackOverflow discussion, but now it's gotten me even more confused.
You should avoid all static methods and instead design a class which does not mandate its lifecycle: it can be a typical immutable POJO with a public constructor.
Then, when you need it as a singleton, use it as a singleton. For testing, use it in some other way.
Usually, dependency injection is the preferred avenue to solve these problems: instead of hard-coding a pulling mechanism for your configuration object, you have the object delivered to any class which needs it. Then you can decide late what bean you will deliver.
Since you are probably not using Spring (otherwise dependency injection would be your default), consider using Guice, which is a very lightweight and non-intrusive approach to dependency injection.
I often need a client bundle and some i18n-ed messages in presenters and views.
I would like to know which is the best way to get them : Injection or Singleton?
Solution 1: Up to now, I used to get the messages using a Singleton :
public interface MyMessages extends Messages{
String key1();
String key2();
...
class Instance {
private static MyMessages instance = null;
public static MyMessages getInstance() {
if (instance == null) {
instance = GWT.create(MyMessages.class);
}
return instance;
}
}
}
FooView.java :
MyMessages.Instance.getInstance().key1();
Solution 2: Would it be better to get it with an injection like this ?
private MyMessages i18n;
#Inject
public FooView(MyMessages i18n){
this.i18n=i18n;
}
The second solution seems cleaner to me but I sometimes get stuck when I need a non-empty constructor which uses some i18n strings:
#Inject
private MyMessages i18n;
public Bar(Foo foo){
/*
* do something which absolutely requires i18n here.
* The problem is that injectable attributes are called
* after the constructor so i18n is null here.
*/
foobar();
}
First, client bundles and I18N messages, while not singleton themselves, share their state with all their instances, so that once compiled to JavaScript and optimized by the compiler it's as if they were singletons. There are a few corner-case (IIRC, when using the WithLookup variants of I18N interfaces) but generally speaking it doesn't buy you anything explicitly treating them as singletons.
So the question basically becomes whether to use GWT.create() explicitly or have the instance injected. I'd say it's a matter of taste, but also technically GWT.create() doesn't play nice with non-GWTTestCase unit-tests.
Finally, as for your latest question, I suppose that by "non-null constructor" you mean that it takes values that aren't dependencies (i.e. value objects); in which case you should probably use assisted-injection rather than constructing the object yourself and then injecting its members (as an aside: how are you injecting the members then?)
I better explain the question with an example.
I have an Interface Model which can be used to access data.
There can be different implementations of Model which can represent the data in various format say XMl , txt format etc. Model is not concerned with the formats.
Lets say one such implementation is myxmlModel.
Now i want to force myxmlModel and every other implementation of Model to follow Singleton Pattern.The usual way is to make myxmlModels constructor private and provide a static factory method to return an instance of myModel class.But the problem is interface cannot have static method definitions and a result i cannot enforce a particular Factory method definition on all implementation of Model. So one implementation may end with providing getObject() and other may have getNewModel()..
One work around is to allow package access to myxmlModel's constructor and create a Factory class which creates the myxmlModel object and cache it for further use.
I was wondering if there is a better way to achieve the same functionality .
Make a factory that returns
instances of your interface, Model.
Make all concrete implementations of the model package-private classes
in the same package as your factory.
If your model is to be a singleton, and you are using java
5+, use enum instead of traditional
singleton, as it is safer.
public enum MyXMLModel{
INSTANCE();
//rest of class
};
EDIT:
Another possibility is to create delegate classes that do all the work and then use an enum to provide all of the Model Options.
for instance:
class MyXMLModelDelegate implements Model {
public void foo() { /*does foo*/}
...
}
class MyJSONModelDelegate implements Model {
public void foo() { /*does foo*/ }
...
}
public enum Models {
XML(new MyXMLModelDelgate()),
JSON(new MyJSONModelDelegate());
private Model delegate;
public Models(Model delegate) { this.delegate=delegate; }
public void foo() { delegate.foo(); }
}
You can use reflection. Something like this:
public interface Model {
class Singleton {
public static Model instance(Class<? extends Model> modelClass) {
try {
return (Model)modelClass.getField("instance").get(null);
} catch (blah-blah) {
blah-blah
}
}
}
public class XmlModel implements Model {
private static final Model instance = new XmlModel();
private XmlModel() {
}
}
usage:
Model.Singleton.instance(XmlModel.class)
Actually, I don't like this code much :). First, it uses reflection - very slow, second - there are possibilities of runtime errors in case of wrong definitions of classes.
Can you refactor the interface to be an abstract class? This will allow you to force a particular factory method down to all implementing classes.
I used to ask myself the same question. And I proposed the same answer ;-)
Now I normally drop the "forcing" behavior, I rely on documentation.
I found no case where the Singleton aspect was so compelling that it needed to be enforced by all means.
It is just a "best-practice" for the project.
I usually use Spring to instanciate such an object,
and it is the Spring configuration that makes it a Singleton.
Safe, and so easy ... plus additionnal Spring advantages (such as Proxying, substituing a different object once to make some tests etc...)
This is more an answer to your comment/clarification to kts's answer. Is it so, that the real problem is not using the Singleton pattern but instead defining an eclipse (equinox) extension point schema that allows contributing a singleton?
I think, this can't be done, because everytime you call IConfigurationElement.createExecutableExtension you create a new instance. This is quite incompatible with your singleton requirement. And therefore you need the public default constructor so that everybody can create instances.
Unless you can change the extension point definition so that plugins contribute a ModelFactory rather than a model, like
public interface ModelFactory {
public Model getModelInstance();
}
So the extension user will instantiate a ModelFactory and use it to obtain the singleton.
If I guessed wrong, leave a comment and I delete the answer ;)