public class Factoryclass
{
public static MyClass returnObject(String str)
{
// Based on the parameter passed it will retrn some class
}
}
If in a Web Application , theer were 100 requests .
Now please tell me how many objects of Factoryclass will be created ??
if you do
Factoryclass.returnObject()
no Factoryclass instances will be created, unless you do new Factoryclass() inside the returnObject method
It entirely depends on the content of your method returnObject(). The fact that it's a static method only means that it is "stateless" and doesn't pull from non-static instance members in order to work. However, you could potentially instantiate a new instance with each and every time it has been called.
The fact that it's a factory leads me to think that is, in fact, the case. However, the nature of the factory pattern would suggest that it should not matter to you whatsoever. If your implementation depends on the fact that this Factoryclass returns multiple instances or the same instance, someone made a wrong decision in making it a factory.
Related
public class MotoXCellPhone {
//assume there's a speaker class
private BlueToothSpeaker speaker;
//why instantiate in constructor?
MotoXCellPhone() {
speaker = new BlueToothSpeaker();
}
//or if i instantiate in a method?
public BlueToothSpeaker useSpeaker() {
speaker = new BlueToothSpeaker();
return speaker;
}
}
why would i want to instantiate a class in another class' constructor? i don't fully understand composition yet so i'm fuzzy on the 'why" of everything
If you instantiate it in the method, you'll create a new one each time that method is called. If that doesn't make sense -- if you want one BlueToothSpeaker object to be tied to the MotoXCellPhone object for its lifetime -- then you need to create it (or inject it) in the constructor.
The argument is as follows: if someone else uses your code, they might not call useSpeakser() and thus speakers might be null. Instantiating speakers within the constructor asserts that it will not be null.
The constructor will run and instantiate BlueToothSpeaker right when MotoXCell is instantiated, whereas the method will only instantiate the new class when it is called.
There are two types of member initialization, each with pros and cons, I'll try to enumerate them:
early-initialization:
done when declaring the member, or within the class constructor
pros:
the created object begins it's lifecycle at the same time as it's "parent", and is available at any time without needing to do any checks
in the case of a worker class, the created object can start working right away
cons:
more CPU/memory used for that object
depending on the context the object might never be used
lazy-initialization:
done on demand, usually within its getter
pros:
the object will be created only when firstly needed, thus reduces its CPU/memory usage
no context dependent, if the member is not needed at all, it will not be created
cons:
you will need to always access the member via it's getter within the "parent" class, otherwise you might run into crashes
care must be taken when dealing with multithreading (e.g. a lock must be used), and this has a performance impact
Depending of the implementation of your class you might choose one over another.
I've seen this code which has two different way its written
public static void main(String[] args) {
Tester.boot();
new tester();
Tester class:
public static tester instance;
public static void boot() {
if (instance == null)
instance = new tester();
}
public Tester() {
System.out.println("test made");
}
What is the difference beetween tester.boot(); and new tester();
Are there any benefits to either?
There are three concepts being displayed here:
Lazy Initialization
Static
Encapsulation (at least the lack thereof)
Tester class:
if (instance == null)
instance = new tester();
That's used when you wish to control the construction of an object. The variable instance controls if new Tester() will be called by boot().
This can be used to implement Lazy Initialization. That's the practice of delaying construction of an object until it is needed. It's typically used when construction is both expensive and not always needed. Here it is delayed until boot() is called. Lazy Initialization is not only used for singletons. Some believe that using Lazy Initialization in java to create a singleton is actually wrong because of how the class loader works. They claim it's a habit ported over from c++ where it made sense. As a pattern, singleton has been controversial enough that some call it an anti pattern.
Tester class:
public static tester instance;
boot(), constructs a Tester object, sets instance to that object (Note: tester should have been capitalized). The fact that instance, which is of type Tester, resides in theTesterclass means thatTesteris [**self referential**][7], like the nodes in a linked list. But, unlike nodes, becauseinstanceisstatic, allTesterobjects have the same copy ofinstance`.
Because boot never puts what it constructs anywhere but in instance, only one boot() constructed Tester object ever exists at any one time, so long as instance is never copied anywhere. It easily could be, because it's public.
So long as instance is never set back to null boot() will construct a Tester only once no matter how many times it's called. Since instance is public it could be set to null at any time by anything that knows about Tester. Doing so would allow boot() to construct again and the old Tester object would be forgotten (garbage collected).
Since Testers constructors have not been made private there is no guaranty that Tester is never constructed by something other than boot(). That means there could still be many Tester objects running around. But they all have one instance in them that may or may not be themselves.
A classic singleton would have Lazy Initialization, be self referential, and be encapsulated in such a way that at most only one Tester object would ever exist. However, There is nothing here that proves this was meant to be a singleton in the first place. This could be a construction optimization gone horribly wrong.
This is sort of implementation of a SINGLETON pattern, in Java.
Look here to understand the concepts behind this pattern click here.
Shortly, you want to use this pattern if you want to have an instance of the class Instance trough all application's life cycle.
To understand it, the key in your code is in the part "if(instance == null)" {instance should be written with lower key, as it should be a class variable}.
If you go simply with the "new ..." any nuber of instances of this variables could be created.
If instead you use the boot method, you are sure that the instance is always the same.
Anyway in the implementation you have written something is missing.
You should refer to this link, where there is also a complete implementation in Java programming language.
boot is useless, you're not showing how Instance is used. But I think it's there to implement a singleton, meaning to assure that only one instance of the class is created. I don't think it's a good implementation as Instance can be used by mistake without being initialized.
When you write new tester() then you're creating a new instance of tester object.
Please follow Java Naming Convention and rename your variables accordingly.
read this comment to know when it makes sense to have an instance and when not.
To be specific--if you use tester.boot() it would set "instance" properly, if you call the constructor directly, it will not.
This is a really broken version of the singleton pattern, to do it correctly the constructor should be made private which makes new Tester() impossible.
Also, the boot method should look a little more like:
public synchronized static Tester boot()
{
if(instance == null) {
instance=new Tester();
}
return instance;
}
and even that is probably iffy.
today i have stumbled on a code which i have seen in my project and was worried looking into it. I dont realize why they have made these as static methods as they change state of object within them.
below is the code
#Controller
CruiseController{
getCruiseSearchResults(){
//prepare cruise serach request, static method in CruiseHelper
CruiseSearchRequest cruiseReq = CruiseHelper.prepareRequest();
...futher impl
}
/** my helper class which has utlity methods */
CruiseHelper{
public static CruiseSearchRequest prepareRequest(){
CruiseSearchRequest cruiseRequest = new CruiseSearchRequest();
// all below methods are static
setCruiseTypeandDestination(cruiseRequest)
setStartAndEndDate(cruiseRequest)
setShipAndDeparturePort(cruiseRequest)
setDurationAndAccesiblity(cruiseRequest)
setPromoType(cruiseRequest)
setResultPreferences(cruiseRequest)
return cruiseSearchCriteriaDTO
}
static void setCruiseTypeandDestination(CruiseSearchRequest cruiseRequest){
/** changing the state of object in static method */
cruiseRequest.setCruiseType("ABC");
cruiseRequest.setCruiseType("Alaska");
}
//.... further static methods as above, all of them
//change the state of cruiseRequest
}
So i know that, above methods should not be static as they all have properties of each request. But the code is working and has not failed on any load test performed.
my important question is : "can this above code be considered ??" and "can this fail, if yes. then in what scenario ?"
Indeed, these methods change the state of an object, but it's an object that is given as a parameter to them, which is perfectly valid and makes sense.
static means that the method is bound to the object definition (the class) and not to any specific object instance. Thus static method cannot change the state of it's own object as it simply does not have an instance to work on (it does not have a this).
I suggest you read this about static and class variable : Understanding Class Members
Static methods are used to imply that that method doesn't need an instance of the class to be called. For example consider the String class. It can still change the state of any object.
replaceAll() is not a static method as it needs an instance to work on. where as valueOf() isn't as it doesn't need a String instance.
I suggest you revisit the basics of Java.
I dont realize why they have made these as static methods as they change state of object within them.
Because they're methods of a class called CruiseController. They are modifying instances of a CruiseSearchRequest, a different class. You could not do cruiseSearchRequest.setCruiseTypeandDestination();, because the method setCruiseTypeandDestination isn't on the CruiseSearchRequest class. So, instead, it receives the CruiseSearchRequest object as a parameter, and since it isn't tied to any instance of CruiseController, it is a static method of that class.
You could make the methods non-static if you moved them to the CruiseSearchRequest class. However, you don't need to. There is absolutely nothing technically wrong with modifying objects in a static method. It might or might not be a good design for your particular program, but it will not "fail".
Methods in Spring shouldn't be static not because they won't work but becouse it is a bad decision in terms of your application architecture. Static methods are wrong decision in terms of unit testing - it is harder to mock static methods than objects. Also I think intensive usage of static methods breaks the concept of dependency injection and the code becomes more tightly-coupled. Here is a nice article on this topic.
I have been going through this tutorial and from what I understand, a singleton class can only be initialized once. Therefore I wrote the following 1 line of code:
public synchronized static DefaultHttpClient getThreadSafeClient {
**System.out.println("this should only happen once!!");**
I then wrote the following lines of code in my MainActivity's button:
HttpClient httpclient = multithreaded_httpclient.getThreadSafeClient();
HttpClient httpclient1 = multithreaded_httpclient.getThreadSafeClient();
I then pressed the button many times and to my surprise i found this in my logcat:
this should only happen once
this should only happen once
this should only happen once
this should only happen once
I thought singleton classe's method only executes once... how is this possible ?
It seems there is a small misunderstanding related to Singletons.
Singletons can only be initialized once, meaning there can only be one instance of it. Of course, the static method will be executed each time you call it, but the returned instance will always be the very same one.
In a nutshell, the Singletons pattern means that:
The constructor of your class is private
You create a public factory method, where YOU take care of:
If it is the first time that an instance is requested, create an instance with new YourClass()
If an instance was already created in a previous call, you don't create a new one, but return the previous one.
So, when any other class needs an instance of that class, they are enforced to call that factory method, since the constructor is private, and inside of that method, you write the code to ensure there is only one instance.
Thats all. With this only one object can be created, so all the possible instances of the object are actually the same, but of course any call to any public method of that object will be normally executed, no matter how many times it is called.
Is calling Class.getInstance() equivalent to new Class()?
I know the constructor is called for the latter, but what about getInstance()?
Thanks.
There is no such method as Class#getInstance(). You're probably confusing it with Class#newInstance(). And yes, this does exactly the same as new on the default constructor. Here's an extract of its Javadoc:
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
In code,
Object instance = Object.class.newInstance();
is the same as
Object instance = new Object();
The Class#newInstance() call actually follows the Factory Method pattern.
Update: seeing the other answers, I realize that there's some ambiguity in your question. Well, places where a method actually named getInstance() is been used often denotes an Abstract Factory pattern. It will "under the hoods" use new or Class#newInstance() to create and return the instance of interest. It's just to hide all the details about the concrete implementations which you may not need to know about.
Further you also see this methodname often in some (mostly homegrown) implementations of the Singleton pattern.
See also:
Real world examples of GoF design patterns.
Absolutely (usually) not.
getInstance is the static method often used with the Singleton Pattern in Java. The new keyword actually creates a new object. At some point there must be a new (although there are a few other methods to instantiate new objects) to actually create the object that getInstance returns.
In the context of an abstract class, a getInstance() method may represent the factory method pattern. An example is the abstract Calendar class, which includes static factory methods and a concrete subclass.
Some abstract classes have getInstance() methods because you can't instantiate an abstract class by using new keyword.
Yes, this is often used in Singleton Pattern. It`s used when You need only ONE instance of a class.
Using getInstance() is preferable, because implementations of this method may check is there active instance of class and return it instead of creating new one. It may save some memory. Like in this example:
public static DaoMappingManager getInstance() {
DaoProperties daoProperties = null;
try {
daoProperties = (DaoProperties) DaoProperties.getInstance();
} catch (PropertyException e) {
e.printStackTrace();
}
return getInstance(daoProperties);
}
public static DaoMappingManager getInstance(DaoProperties daoProperties) {
if (instance == null) {
instance = new DaoMappingManager(daoProperties);
}
return instance;
}
For start:
newInstance() is a static method. This means you can access to it without creating new class directly! And it creates that class itself "with necessary inits" (via an inner new myClass()). This means you can add some newInstance methods (newInstance4usage1, newInstance4usage2,...) for different needs that per static method creates class with different initialization.
Sometimes, this helps class's user (final programmer) to creating class without any worry and very comfortable.
This helps really when the init process is complex or has important or or usual levels. this method don't prevent from creating class by new keyword.
I like it!
Excuse me for slow answering, I am typing with my mobile phone!