One of the most useful things about object oriented programming is polymorphism. In fact, it makes our software to have different behaviors without the need to explicit it in the code.

For instance, you are writing a code to make a credit card transaction. If it is a VISA transaction, you should execute one specific action, if it is a MASTERCARD transaction, you should execute another specific action, so, the first thing you think to do is:

That's not a good design, is it? Probably we need to write a lot of code for each card network, besides, if I want to add support to another card network, I will need another if. Someday this code is going to be little demon.

So, what should I do? Well, in oriented programming, there is something what people call "polymorphism", and what they say that the same method could have several behaviors. Well, that's just what we need for this situation. So, how can we begin?

Well, we are going to have an interface called Payment, having a method, of course, called "pay":

That solves our first "pay" method, which was going to be very big (very!!)

But, if I want to do something dynamically? For instance, I don't want to use ifs in my code to choose which instance of a Payment I am going to use, I just want to tell the code to give me an instance based on some variable, like:

When we inject the object javax.enterprise.inject.Instance<Payment> with the qualifier @Any, every instance of Payment will be available for you to choose and use. The nicest thing is: now CDI will control the creation of your objects, you don't need to write your own factory, you can also inject resources into your Payment subtypes and choose any CDI scope you want.

That's not a new thing in CDI, but, most people still don't know how powerful CDI is.