I know, we already discussed this on different coderanch topic but i am still not convince!
Hence i am putting my question one again, in detail mode.
Lets say we have situation to implement a service class
Now it is clear that this service class is fully stateless.
Now their is different approach to access/design this class.
Way 1: Create a new instance every time
So people who hate static stuffs in their application, they create the instance of this class every time.
which could be the first way.
Way 2: Use static methods When we look on the all stateless class in JDK, String, Integer, Collections, etc
All use static methods in them, which is a nice way, since their is no state to maintain then why to create instance every time.
use static methods as JDK do.
Way 3: Using singleton class very much like Spring do Now this sound bit strange but this what we are doing now days in most of the web application as Spring is the most widely used java framework we have in market.
As spring do, it create a single instance of all stateless beans(unless prototype is not enabled)
Note: I know its not like a java singleton pattern, but if you have a single application context file in your application, then it is not different either.
Now way 3 sound more promising as we are not creating instance every time and we are not using static method either.
what we can have is (if we are not using spring !!)
Please share your thoughts.
Lets have discussion on following aspects
2. How easy it is to use.
I think the choice would depend a lot on whether we want to extend the behavior of StudentService, personally since this class doesn't seem like a plain utility class (like Math class) I would want that other classes could extend it like
So I wouldn't want StudentService to be final, have a private constructor and I wouldn't have its methods static (Giving PrivateStudentService an opportunity to override)
So Spring takes care of my needs as it gives me a singleton (fewer objects, only 1 in case of single bean declaration), without me actually making the class singleton, thereby allowing me to have PrivateStudentService as well.
Cheers, Joy [SCJP 1.4, SCBCD 5.0]
get high on alcohol, algorithm or both
Due to some reason i cant used spring in my application.
So i m trying to find the way, which similar to spring.
same time i also want to know, do this whole 'spring concept of DI' is worth of something.
Having said that, a protected constructor can provide the needs, what you are looking from spring in your example.
Idea is to know the best way, when we cant use spring.