why use getInstance - java

A lot of the publicly available Java APIs seem to use getInstance in order to generate and return an object. I'm curious about why this is so -- why not just use default/parameterized constructors instead?
Is there an associated design pattern?

I suggest to read "Effective Java" by Joshua Bloch, Item 1 "Consider static factory methods instead of constructors". He led the design and implementation of numerous Java platform features, he knows why.

It is associated with Singleton Pattern.
Many times there are also Factory Methods which help you in creating objects.
For example: Boolean.parseBoolean("true");
Advantages of Factory Methods are they are more verbose and easy to grasp than a series of constructors.

Another example (apart from the singleton or multi-ton pattern) is if you need to do something in the constructor that is generally not recommended, such as registering a listener or starting a thread:
class Whatever {
private Whatever() {} //private constructor
public Whatever getInstance() {
Whatever w = new Whatever();
startSomeThread();
return w;
}
}

Yes....It is associated with both Factory and Singleton pattern. Factory pattern is used to decouple the object creation logic from the business logic and Singleton pattern is used to maintain only a single instance of an object through out the application.

"why not just use default/parameterized constructors instead" because at the point you invoke the constructor it is already too late to ensure the Singleton Pattern constraint to have only one instance. The whole point is to have controlled access to a single instance and avoid multiple instances. The only way to do that is to use access modifiers to prevent the constructor from being accessible.

To save you the trouble of looking up concrete reasons...
This is a case of the Factory Method pattern. The most common reasons to use it are:
If construction is too complex to handle in a constructor
If construction requires actions that are not permitted or desired in a
constructor
To decouple the type of the product ("interface") from the actual implementation ("class").
For performance or architechtural reasons, such as to perform partial specialization at construction time
For clarity/readability
There is some overlap between these reasons. In fact, often all four apply. Partial specialization (4) pretty much requires decoupling of type and implementation (3).

As it has been said, it's a matter of some pattern designs "requirements" to provide an easy/secure solution.
But you should avoid the using of "getInstance" (java.lang.Class.getInstance()' and 'java.lang.Class.NewInstance()') as far as possible in terms of Dynamic Instantiation, because Dynamic instantiation is slower than a regular Class invocation or Method call.
Use it only when it is necessary!

Related

When should we use the factory method pattern? (instead of composition)

As per GOF book, Factory method pattern
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
Structure of the pattern
public abstract class Factory {
public abstract IProduct createProduct();
private void performCriticalJob(){
IProduct product = createProduct();
product.serve();
}
public void executeJob(){
//some code
performCriticalJob();
//some more code
}
}
public interface IProduct {
public void serve();
}
Factory needs an object (whose concrete class is not known or whose concrete class may change as per the different application type ) to perform a task.
As it does not know which class to instantiate, one standard contract is set for the type of object needed, this contract is put in an Interface.
Base factory class declares an abstract method to return an object of type as above defined interface.
It lets subclasses decide and provide the implementation of object creation.
For completion of the task it needs an object which it simply fetches by calling the abstract method.
Question Favour Composition over inheritance.
Factory method above uses inheritance to get the concrete products. Also subclasses need to be implement the createProduct which will create and return the ConcreteProduct. Instead of Subclassing the Factory class, if abstract method is removed from it (which makes the Factory class as non abstract class). Now Factory class can be composed by the new classes and concrete product objects can be injected in it as below example.
To achieve the intent in the scenarios as defined by Factory method pattern why just normal polymorphism is not being used as below ? I know factory method pattern has something more which I am missing but going by the favouting composition over inheritance, i find the below way ,to solve the same problem in same scenario , a better way over the way as in Factory method. What is the advantage of Factory method over the method below ?
public abstract class PolymorphismWay {
private void performCriticalJob(IProduct product){
product.serve();
//some code
}
public void executeJob(IProduct product){
//some code
performCriticalJob(product);
//some more code
}
}
Now instead of asking users to create child factory classes and returning the concrete object of product by implementing the createProduct method, users can directly provide the object of concrete classes implementing IProduct to executeJob.
[EDIT] Thanks for the answers and comments but same thought as expressed in comments and answers I also had which also brought some confusion. I studied the GOF factory method pattern. It has used an example of a Framework for applications creating documents of various types. My questions are doubts those arouse after this study.
The sites and blogs are based nothing but the reflection of the understanding which the authour has for the pattern, he / she may or maynot have read, understood the actual intent of the pattern. Understanding the classes is not the main objective. Design pattern should be studied considering what scenario and what problem comes for which the best solution following the good OOP principles ( or violating them the least and voilating them along with having a very good reason to do so). That best solution is the solution as explained by any design pattern. GOF is a standard book which explains it quite well. But still there are few gaps or doubts which is the main reason for this question.
I know factory method pattern has something more which I am missing but going by the favouting composition over inheritance, i find the below way ,to solve the same problem in same scenario
There are several advantages that you get when using the Factory Method pattern instead of plain old composition as shown in your question :
1. Separation of concerns and open-closed principle : You create one factory subclass for each related group of objects. This factory subclass is responsible for creating only those products that belong to a particular group. ABCProductFactory will only be concerned with creating ABCProduct1, ABCProduct2, etc. CDEProductFactory will only be concerned with creating CDEProduct1, CDEProduct2 and so on. For every new product group, you create a new subclass rather than modifying an existing class. If you went with the composition approach, some other class would be responsible for creating the product and passing it into your Factory. As your product variety increases to say ZZZProduct1 and ZZZProduct2 and so on, this class would soon explode to a huge size with too many if-else conditions to check which product subclass to create. You would eventually realize this and define one class for creating each related group of products.
2. Product creation and product processing has a contract : The factory method pattern is very similar to the template-method pattern in this case as it specifies a template for the operations that need to be performed on an object after it has been created. This allows you to ensure that once a product is created, it will always go through the same steps as any other product created by the factory. Compare this to the Composition example in your question where there is no fixed contract for what steps an IProduct should go through once it has been created. I could create a class called Factory2 with a single public method called performCriticalJob. Nothing forces me to have an executeJob method in Factory2. Even if I add an executeJob method to Factory2, nothing forces me to call performCriticalJob inside executeJob. You could fix this issue by using the template pattern.
It should be clear by now that the Factory Method pattern basically binds the object creation and object processing together in one class. With your composition example, you would have a lot of moving pieces and no one governing how they should work together.
Bottom line : In your case, use the Factory Method pattern when you want object creation and object processing to have a fixed contract such that all objects go through the same processing once created. Use your composition example where there is no contract needed for the steps to be followed after the object has been created.
Your problem is, you are insisting that your Factory class has only ONE kind of clients who always use the class by either extending it (the code #1) or passing a newly-created IProduct to its methods (the code #2). The whole purpose of this kind of clients is to make the Factory the ability of receiving a newly-created IProduct.
How about normal clients who don't care about all of the things above! These even don't care whether the class is Factory or not. Thus, they don't want a method requiring an IProduct as in your code #2.
Indeed, you should rename your Factory class to something else (e.g., XXX), the class is not "factory"! But some of its methods are "factory". You see, the pattern name is "Factory Method", not "Factory" or "Factory Object". In contrast, in Abstract Factory pattern, an abstract factory is really a factory object.
P/S: a proper composition approach is passing an abstract factory into the constructor of XXX.
Since we know the Factory Method Pattern relies on inheritance, this problem is much easier to reason about if we begin without the Factory Method piece and simply ask, when should we favor inheritance over composition?
We already know the answer to that question is, "not often" because the GoF has told us to favor composition in general. Yet there are real-world scenarios where inheritance exists. The animal kingdom may be the quintessential example. When inheritance actually occurs within a domain, it makes sense to model it the same way in our code. And that's when we should consider the Factory Method Pattern as well. Consider it only when you've already decided that inheritance is appropriate to the context. First choose inheritance, then choose the creational pattern. Don't introduce Factory Method and then be forced into an inheritance relationship that otherwise wouldn't apply.
A more opinionated answer is: never use the Factory Method Pattern in modern code. Stick with composition relationships, all wired together within a dependency-injection container. The GoF patterns are not advice. They are a collection of designs from the 1980s. Similar to the way Singleton is now considered to be more anti-pattern than pattern due to its negative side effects, Factory Method has very little applicability in modern code. In those rare cases where it may be appropriate, you'll know it because you'll already be using inheritance.
Read again the definition you've provided:
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
Which a bit contradicts your first statement:
Factory needs an object (whose concrete class is not known or whose concrete class may change as per the different application type ) to perform a task
The factory purpose is creating objects, not performing tasks.
In fact, event if it will perform a task it's only to be able to create the object for you.
After you get the object from the factory, you can perform your critical job.
And about Favour Composition over inheritance, the factory method can compose the object for you as well and deliver back an object composition.
There are many good examples of factory pattern - for example in Wikipedia and blackwasp
Edit - Concerning the GoF Application example
The GoF example of the Application uses a Template Method for the Factory Method.
the Application defines the factory method and some operations around it, but the sub-classes of the Application decide which Document to create.
You have suggested, not to use factory method. Instead, to create the Document somewhere else and "injected" to the Application (a.k.a dependency injection).
You have not described where will the Document be created (it could still be a factory).
Now the Application sub-classes doesn't have any control on the creation of the Document. This changes the behavior and design of the system completely.
It doesn't mean that its bad or good, it's just a different approach.
In real-life scenarios you have to carefully examine the problem at hand and decide which design would fit the most.

Factory Method Design Pattern `static` modifier must need or not

I'm studying about Design patterns. I have studied about Factory Design Pattern in java and i have Some things I didn't understand well and I'm writing them following.
Is there any different between Factory Design Pattern and Factory Method Design Pattern.
I saw in some examples, Factory class's get method is static and some examples its not static. What is the correct way.
Any help would appreciate.
I'm not too deep in design patterns in the sense that I did not ingest massive books discussing them in much abstraction, but I certainly have an idea of what they are and know how to apply them. Here is my understanding of these two patterns:
Factory is a pattern that delays the instantiation of an object by handing an object that knows how to construct others objects.This can have several advantages going. For example, let's say you are writing a theading pool library. A pool contains objects that can perform certain actions, and you want to be able to create pools of any size. Each object of the pool must be a distinct object. You could ask the user of your pool to give you as many objects as they want in the pool, but you can also ask them for a single factory that you will use to instantiate the objects yourself. This way, you can also dynamically change the size of the pool, destructing or regenerating objects, etc... It gives all the flexibility you need without knowing anything about the objects your pool is holding.
Factory method is different. Let's say you have a big constructor with a lot of parameters. Some of these parameters may have default values, or you may have various way to configure this class. You could certainly add a constructor for each typical configuration (set of parameters) but this wouldn't be user-friendly as all the constructors share the same name. To make it easier, you could have static methods that just call the constructor with the appropriate configuration. The advantage is that you can name these methods (defaultHttpClientForProd, defaultHttpClientForDev etc...). Another use-case is if you have a massive class hierarchy, say an abstract class Car extended by dozens of classes. You could use each individual constructor to build your dream car, but you would have to look at each and every page of the catalog to decide which one you want. You could alternatively have a single page that summarizes all the cars available, this would be a class containing a lot of factory methods, making them more discoverable.
For your second question about, I would say it depends. If you don't need to customize your factory too much or inject a lot of context, a static method with some parameters will do the trick. If you want your factory to be more configurable, a class with attributes and an instance method will be better.
To be specific to your questions:
Abstract Factory & Factory Method are two different design patterns. Refer to Gang of Four (Design patterns) for detailed explanation. The key difference is Abstract Factory or Factory is about creating families of related objects (note the word family meaning group of objects) whereas Factory Method is providing a creational method to create one particular type of object (not family), which can be implemented by multiple factory implementation class. Essentially, Factory Method is used in implementing Factory or Abstract Factory pattern but not the vice-versa.
As far as static method is concerned, it is not mandated by the pattern itself. It is specific to Java & hence static modifier is used to make sure Factory's getInstance() or any creational method is Singleton. You don't want multiple instances of Factory and hence in Java, you implement by having static instance of Factory and therefore, you will need static method to return the static instance.
Different tutorials seem to mean different things by the factory design pattern. I would say that the ones in your links are both simple factories. I think this post explains the difference simply: Simple Factory vs. Factory Method vs. Abstract Factory
Simple factories can be identified by the use of a static method to create different subclasses, usually with some kind of if/else or switch structure. The example in the second link doesn't actually use a static method, but it can easily be made static without changing much.
In the Gang of Four book, the Factory Method Pattern is defined as:
Define an interface for creating an object, but let subclasses decide
which class to instantiate. The Factory method lets a class defer
instantiation it uses to subclasses.
Because of the use of subclasses, static methods will not work here because they can't be overridden. The shape example done this way would be more like:
public interface ShapeFactory {
Shape getShape();
}
public class CircleFactory implements ShapeFactory {
public Shape getShape() {
return new Circle();
}
}
public class RectangleFactory implements ShapeFactory {
public Shape getShape() {
return new Rectangle();
}
}
ShapeFactory shapeFactory = new CircleFactory();
...
Shape shape = shapeFactory.getShape();
Here, we can separate the creation of the factory from its usage. The factory can be created in one class and then passed to another, so a class can create different types of objects by being configured by another.
Or in Java 8, we can just use:
Supplier<Shape> shapeFactory = Circle::new;
...
Shape shape = shapeFactory.get();

code reuse in Methods.class vs strategy pattern and dependency injection [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Status: Answers of Fendy and Glen Best are equally acceptable and honored by me but since one can be accepted and bounty be given, I choose Fendy's answer.
Scenario:
If I have some code that has to be reused many times in many classes (rarely with minor parameter changes which is obvious) and concurrent threads, Which approach to go for?
The code that has to be reused can be any sane thing (with appropriate care of static and non-static context in mind and method making techniques). It can be an algorithm, A DB method doing connect,operate,close. Anything.
Make some class like MyMethods.class and put all those methods in it.
1.a. Make methods static and call (by all classes and concurrent threads) directly as MyMethods.someMethod();
1.b. Make methods non-static and at the time to call them, instantiate the whole class by MyMethods mm = MyMethods(); mm.someMethod();
Use Strategy pattern stated at https://en.wikipedia.org/wiki/Strategy_pattern (code attached here with).
Use dependency injection stated at https://en.wikipedia.org/wiki/Dependency_injection#Java
Problems:
Some people would say Unit test http://en.wikipedia.org/wiki/Unit_testing wont be possible with this approach, will make trouble in swaping out latter. if you want to test your class and use a mock version of the dependency
1.a. Will there be any problems with concurrent calls or multiple classes? specially in JDBC static methods for just an example?
1.b. I think it would make too much memory load as a whole class would be instanticated many times just to call one or two methods
Thats way over my head, do explain that and or any advantages/disadvantages
I do Not want to use a framework in context to this question.. Thats way over my head, do explain that and or any advantages/disadvantages
Awaiting any other strategies or recommendations, if any.
Request: Please only answer if you are experienced and know the implications deeply and can comprehensively, with your answer, help me and the community as a whole!
Code:
/** The classes that implement a concrete strategy should implement this.
* The Context class uses this to call the concrete strategy. */
interface Strategy {
int execute(int a, int b);
}
/** Implements the algorithm using the strategy interface */
class Add implements Strategy {
public int execute(int a, int b) {
System.out.println("Called Add's execute()");
return a + b; // Do an addition with a and b
}
}
class Subtract implements Strategy {
public int execute(int a, int b) {
System.out.println("Called Subtract's execute()");
return a - b; // Do a subtraction with a and b
}
}
class Multiply implements Strategy {
public int execute(int a, int b) {
System.out.println("Called Multiply's execute()");
return a * b; // Do a multiplication with a and b
}
}
// Configured with a ConcreteStrategy object and maintains
// a reference to a Strategy object
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return this.strategy.execute(a, b);
}
}
/** Tests the pattern */
class StrategyExample {
public static void main(String[] args) {
Context context;
// Three contexts following different strategies
context = new Context(new Add());
int resultA = context.executeStrategy(3,4);
context = new Context(new Subtract());
int resultB = context.executeStrategy(3,4);
context = new Context(new Multiply());
int resultC = context.executeStrategy(3,4);
System.out.println("Result A : " + resultA );
System.out.println("Result B : " + resultB );
System.out.println("Result C : " + resultC );
}
}
Your question actually has two meanings.
that has to be reused many times in many classes
It can be a context of design pattern (reusable component) or memory cost (class instantiation). Talking from two different perspective:
Memory Cost (I had little experience on this, but let me share my experience)
This section actually only cover 2 kind of instantiation.
First is static (or DI instantiation in composition root)
Eager instantiation, means all class will be instantiated when application start
One time instantiation only
Non-static
Lazy instantiation, means class will only be instantiated when needed
One time instantiation every use
In short, static will cost high if the class is many, and non-static will cost high if the request is high (inside for loop, for example). But it should not make your application heavy. Most operation in java / csharp are creates objects though.
Class Reusability
1 - mega monolithic code (one god class able to do almost everything)
Advantages:
Easy to search for code (still depends though), you know that every logic lies there so you just need to look at that big class
If it is static, you can just call it anywhere without worrying about the instantiation
Disadvantages:
Any modification for one method creates risk for error in other places
Violates SRP, means this class can be changed by various reason, not only one
Especially in versioning, it is harder to merge if modification happen in separated branches, resulting effort in synchronize code
1a / static class / singleton pattern
Advantages:
Easy to use
Can be used anywhere (just reference and call, and done)
Not need to instantiate object
Disadvantages:
Hard to unit test (it is hard to mock, and at latter time, you will find it is taking time to prepare the test environment. Especially with data
If stateful (has state), it is hard to determine current state, during debugging. Moreover, it is hard to determine which function changes the state, in can be changed from everywhere
Tend to have much parameters (maybe around 5-11)
Some point about static class: see this question
2 strategy pattern
Actually this has the same design with 3 or composition over inheritance.
3 dependency injection
Advantages:
Easy to mock and unit test
Must be stateless. It is easier to debug and unit test if the class is stateless
Support to be refactored
The disadvantage:
Hard to debug for those who does not familiar with interfaces (everytime you redirect to the method, it goes to interface's)
Creates layering which will resulting to mapping
State / Stateless
I think states plays important rules in your application design. Usually developers try to avoid having states in business logic code, such as:
// get data
if(request.IsDraft){
// step 1
// step 2
}
else{
// step 1
// step 3
}
Developers tend to put the logic in other stateless class, or at least methods such as:
// get data
if(request.IsDraft){
draftRequestHandler.Modify(request);
}
else{
publishedRequestHandler.Modify(request);
}
It will provide in better readability, and easier for modification and unit tests. There is one design pattern state pattern or hierarchial state machine pattern too, especially to handle some cases like this.
Single Responsibility Principle
IMHO, this principle is has the most benefit if followed. The advantages are:
In versioning, the changes are clear about which class has been modified and why
In DI, several smaller classes can be wired up, creating flexibility in both usage and unit test
Increase modularity, low coupling and high cohesion
TDD (Test Driven Development)
This design does not guarantee your code free of bugs. In cons of costing time at design phase and layering effort, it has the benefit of:
Easy to mock object for unit test
Easier to refactor because of unit test and modularity
Easier to maintain / extend
Some useful sources
Service Locator Anti Pattern
Using Decorator for cross-cutting concern
My 2 cents:
The benefit of using interface (also apply for composition ofer inheritance)
Doing top down design / DI design
Final Thoughts
Those designs and strategies are not the key which will determine your application structure. It still the architect who will determine it. I prefer to follow some principles such as SOLID, KISS and GRASP, rather than deciding what is the best structure. It is said that Dependency Injection follow the most of those principles, but too much abstraction and incorrect components design will resulting the same with the misuse of singleton pattern.
1.a. Make methods static and call (by all classes and concurrent threads) directly as MyMethods.someMethod();
1.b. Make methods non-static and at the time to call them, instantiate the whole class by MyMethods mm = MyMethods(); mm.someMethod();
The choice between these two depends on the functionality of MyMethods.class. If MyMethods is supposed to be stateless then it's a good approach to go with static methods. Otherwise, if one method call depends on another and MyMethods have states (i.e. non-final fields) then use the second option.
Use Strategy pattern stated at https://en.wikipedia.org/wiki/Strategy_pattern (code attached here with).
Use this pattern if MyMethods are to be extended with different classes for different purposes and if you select which code to run depending on your context. As the wiki says, if you the algorithm to be used is not known before the runtime (depends on some conditions) this is the way to go. According to your specification of MyMethods you do not have such problems.
Use dependency injection stated at https://en.wikipedia.org/wiki/Dependency_injection#Java
Same answer as above. The thing with dependency injection is in inversion of control. A class that uses MyMethods does not know about actual the implementation of MyMethods, but the injection of real implementation is delegated to some higher-level authority. It abstracts external dependencies from the context where it is going to be used. Again, if MyMethods are to be stateless and constant (not planned to change, and the behavior of methods within the class does not depend on the context where they are used) you do not need these patterns as it would just mean over engineering.
I would conclude that you should use Strategy or DI pattern if logic of MyMethods depends on the context from which they are run. If this is constant (e.g. Java's Math class does not care who or in what context someone calls sqrt(), max() or pow()) then static methods are the way to go.
Regarding problems:
Problems you stated are not present when you use MyMethods with static methods. You will have to test whether your methods return correct values for particular arguments and that's it. I don't believe that there would be much more trouble testing actual implementation of Strategy in Strategy pattern or implementation of interface that are injected through Dependency injection. What might be harder is testing the classes that use strategy because sometimes it's not easy to recreate the context in which particular strategy will be executed as it often depends on user input, but it's definitely not impossible. Dependency injection is, as far as I'm concerned, great for testing because you can separate unit under test from dependency which you can easily mock.
The main question: code reuse
If I have some code that has to be reused many times in many classes (rarely with minor parameter changes which is obvious) and concurrent threads, Which approach to go for?
Because you're not considering any cut-&-paste, I think you mean:
... reused many times by many classes ...
What you're asking is nothing special or specific. It's common that code is reused, either within a single app or across multiple apps.
The common answer: use object-oriented design/programming. Put the code in a class, create an object as an instance, call the object...
1a. Reuse via static methods:
Make methods static and call (by all classes and concurrent threads) directly as MyMethods.someMethod()
If your class is stateless (no instance variables), this is a great approach.
If your class has class-level state (static instance variables only), but the variables are read-only (immutable), this is a good approach.
If your class has class-level state (static instance variables only) and the variables change values (mutable), then this can be an appropriate approach. However, if you want your class to be accessible from multiple threads, you must make it thread-safe: make your methods synchronized, or have internal code that synchronizes (mutually-exclusive thread access) for all data reads and writes.
If your code has object-level state (non-static instance variables), this approach won't work - impossible to access non-static instance variables without instantiating an object.
1b. Reuse via non-static methods, with object instantiation:
Make methods non-static and at the time to call them, instantiate the whole class by MyMethods mm = MyMethods(); mm.someMethod();
If your class has static instance variables only, this is a poor approach, because instantiating the object achieves nothing
If your class has non-static instance variables - this is the only approach. Mandatory to instantiate an object to access the variables.
If the instantiated objects are to be used across multiple threads, they should be (in order of preference):
stateless (no instance variables) - really an option for 1a - no need to instantiate
immutable (read-only non-static instance variables)
synchronized on all data reads & writes
Use Strategy pattern
Strategy pattern can be good practice. But it has little to do with your overall question. Strategy pattern is used for a specific reason - to swap the implementation of algorithm/processing logic "on-the-fly" without impacting the caller.
Use dependency injection
Dependency injection is used for these reasons:
Factory & object cache functionality: removes from your code responsibility for object creation, caching and lookup
Intermediation for object sharing: allows various classes to share the same object instance (stored in a given scope/context), without the two classes directly passing the object between themselves
"Wiring control" between object instances - setting up object associations, and under CDI, support for interceptor, decorator and observer patterns
This can be very good practice, if used appropriately. In your case, this could only ever apply under option 1b. Dependency injection is all about object instantiation and provision into variables.
Problems:
Some people would say Unit test wont be possible
Mocking frameworks (and hand-coded unit testing) deal with replacing classes with mock logic, all the time. It's a very normal scenario. You can extend a class to mock it's logic - if it doesn't have final public methods. Also, you can transfer method declarations to an interface, have the class implement the interface, and then mock by implmenting the interface with a different class.
In other words, this is not a constraint/force affecting any of your options
1a. See above
1b. Memory Load
I think it would make too much memory load as a whole class would be instanticated many times just to call one or two methods
A small issue. Depending on the data within each object instance (the instance variables), each object instance could be as small as a dozen bytes or as large as megabytes - but usually slanted towards the lower end (often < 1kB). The memory consumption of class code itself is not replicated each time the class is instantiated.
Of course, it's good practice to minimise the volume of objects, according to your requirements - don't create a new instance if you already have a useable one. Create fewer object instances and share them across your app - passing them into constructor methods and setter methods. Dependency injection is a good way to share object instances "automatically" without passing them into constructors/setters.
See above
See above

Should I use a pool of objects, a singleton or static methods in a multi-threaded environment?

I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?
What would be the difference between implementing this class as a singleton and just using static methods?
What would the effect of thousands of users accessing this object/these methods be?
I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.
Infact instead of singleton you can make the methods static.
Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.
discussion on Singleton vs Static methods is here
As the name suggests, singletons are used to have only one instance of the object present at the time. So singleton does have a state, but you're accessing to that one state wherever you're calling your singleton.
So if you don't need any state saved in your class/method I'd suggest to use static approach.
No need to use singleton here (since you do not need a state), you can use static methods.
Singleton in principle offers more control by allowing a state. There won't be much difference in your case, but static methods will be easier to implement and use.
What would the effect of thousands of users accessing this object/these methods be?
Again, not much difference in both cases, but in Singleton you can have a state, and if you do not implement carefully, your code will be non-thread-safe. Every user calling the static method gets its own "instance" of the method (I think this is what you ask), so no risk of running into thread-safety problems there.
As has been stated before, given that your class doesn't have object state, static methods would work just fine.
However, consider the following - Depending on the overall design of your system, you may want to be able to specify a different implementation of the methods. This is usually done with either subclassing (...), or interface implementation (now the preferred method) - look up the strategy pattern. In either case, being able to provide alternte implementations would require you to not use static methods, but to have an (empty) object to call methods on.

Why use a singleton instead of static methods?

I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.

Categories