1

I have 2 separate Interface Implementations and based on a setting I have stored in my database I want to use either one (create object of specific impl class and execute methods).

So,

If setting = 1 then use Interface Implementation 1 Else use Interface Implementation 2

What is the best way to do this? Is there anyway to dynamically instantiate an object of the correct interface implementation based on a variable value?

2
  • We'll need more background to the problem; it looks like you're trying to find a solution to the wrong problem. What will the two interfaces do? What will they be used for? Why do you need to use two separate interfaces? Commented Dec 22, 2011 at 15:21
  • 2
    @thecoop it seems like a normal situation for me ! Commented Dec 22, 2011 at 15:22

2 Answers 2

3

You could use the factory design pattern.

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

1 Comment

which hides an if-else or switch - but this is acceptable at initialization time. For everything afterwards you should rely on polymorphism.
2

Yes, you'll want to have a look at the Factory pattern.

In essence, you delegate the creation of the actual object to another object (called the factory). When asked for an instance of the object, the factory would look at the database value and create the appropriate instance.

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.