6

Here's what the interface of a strategy could look like

public interface Strategy
{
    public void doStuff(Object o);
}

And here's a possible implementation

public class StrategyImpl implements Strategy
{
    @Override
    public void doStuff(Object o)
    {
        //Do things with o
    }
}

Now, I might have hundreds of objects using the implementation StrategyImpl. Should a new instance of StrategyImpl be created for all of those hundreds of objects or is there a better way?
I've read on here that singletons should not be used to save memory, but it seems really unnecessary to create hundreds of identical instances. Maybe the best solution wouldn't be a singleton but something along the lines of it.

How should I go about creating strategies? Should I not bother myself with these types of issues?

Community
  • 1
  • 1
EFTH
  • 405
  • 4
  • 13
  • This is what Dependency Injection is for. Use guice/Spring to handle injecting your one instance of `StrategyImpl` to all dependent objects. – spinlok Apr 05 '14 at 10:11
  • Strategy interface implementations seem like a great use for immutable/stateless singletons. The frameworks mentioned by @spinlok use singletons a lot. – mhvelplund Jan 09 '18 at 07:25

1 Answers1

-1

Usually a new implementation should be better. Singleton is a lot based on implementation of the Strategy with conditions that there should be e.g. no private attribute. That would work well for smaller and simpler strategies, but I won't recommend relying on that. Some more information about why singletons are bad in general can be found here

Community
  • 1
  • 1
Tomas Pastircak
  • 2,829
  • 14
  • 28
  • I read the top answer from your link, and I have a few comments for others reading your answer later: 1. Singletons don't _have_ to be a global instance. The singleton could be owned by a factory and passed to new instances. 2. This makes no sense. Does every class with a constructor violates the single responsibility principle? 3. *Nonsense*. They simply provide an immutable instance of code that can be shared. 4. Their state should be immutable. You make it once, and that's it. – mhvelplund Jan 09 '18 at 07:22
  • @mhvelplund 1) Singleton is a design (anti)pattern which is from definition one instance in system, no matter if called directly or via factory, so yes, it is one global instance. 2) There is a difference between being constructed and being responsible for construction - objects with constructor are not generally responsible for the construction as long as the constructor is not called from within them - which is the case for singleton (anti)pattern. Learn more about SOLID principles. No idea what 3 and 4 refers to. – Tomas Pastircak Feb 26 '18 at 14:12