3

How to implement singleton without using static/global variable? Possible?

This is an interview question...

1
  • Why are you concerned with using the static global variable? As long as you are using the singleton method correctly, you are fine. Commented Nov 5, 2010 at 3:08

3 Answers 3

4

Dependency injection is one possibility. Since your question is not specific to any programming language, I am not posting framework specific syntax (such as Ninject)

Sign up to request clarification or add additional context in comments.

4 Comments

With DI you're just shifting the storage from a static variable to the DI container. Also, you're losing a lot of the benefits of singletons--enforced single instances. With DI you're relying on users to always use the DI framework which can internally enforce single-instance rules, but cannot prevent code outside the DI from creating additional instances.
as an answer to an interview question, which itself is more of a 'lets see how the candidate thinks' type, this is good.
@akf, for an interview, it's important to be able to explain the positives and negatives of the proposed approach.
Agreed to your point of view. Since the original question was more on ways of implementing Singleton, I suggested this as one of the possibilities. The fact however remains that nothing prevents me from skipping the dependency injection framework and creating an instance of the class.
2

Store the singleton in a file.

Comments

2

No. You need a place to store the singleton.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.