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

josamiti :

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!

Nghia Bui :

You can apply the Factory pattern:

class Factory {
    public MyInterface a() { return new MyInterfaceA(); }
    public MyInterface b() { return new MyInterfaceB(); }
}

public class MyClass {
    private Factory factory;
    public MyClass(Factory factory) { this.factory = factory; }
    public void firstMethod() {
        factory.a().method();
    }
    public void secondMethod() {
        factory.b().method();
    }
}

Inside the Factory class you can cache the objects created if necessary.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134460&siteId=1