简体   繁体   中英

Singleton with the strategy pattern

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?

Usually a new implementation should be better. Singleton is a lot based on implementation of the Strategy with conditions that there should be eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM