dimanche 19 mai 2019

How to use more implementations of one interface in one class?

I would like to ask for your help regarding the following problem.

There is an interface which has more implementations:

public interface MyInterface {
    void method();
}
public class MyInterfaceA implements MyInterface
public class MyInterfaceB implements MyInterface

and there is a class which uses these implementations of the interface in its different methods:

public class MyClass {
    public void firstMethod() {
        new MyInterfaceA().method();
    }
    public void secondMethod() {
        new MyInterfaceB().method();
    }
}

My problem is that I wouldn't like to create new specific instances in the methods of the class, so somehow I would like to hide which implementation is used.

Do you know a nice solution for this? Is there any design pattern what I can use? How can I hide the concrete implementations or I cannot?

Thanks for your answers in advance!

Aucun commentaire:

Enregistrer un commentaire