If you are using Spring, there is a better way to achieve this. Although it can not be called as Factory Pattern. You can create @Bean for each of the implementations and use specific one whenever required. Or you can annotate each of the implementation class with @Service, @Component, @Repository as per the scenario with unique qualifier names and @Autowired them with @Qualifier("qualifier") anotation. Ex:
interface MyInterface {
// method signature
}
@Component("myClass1")
class MyClass1 implements MyInterface{
// code
}
@Component("myClass2")
class MyClass2 implements MyInterface{
// code
}
public class Main{
@Autowired
@Qualifier("myClass1")
MyInterface myClass1;
@Autowired
@Qualifier("myClass2")
MyInterface myClass2;
public static void main(){
myClass2.func1();
myClass1.func2();
}
}
If you don't want to use Spring dependency injection you can do so
interface MyInterface {
public void invoke();
}
class MyClass1 implements MyInterface{
public void myMethod(){
}
public void invoke(){
myMethod();
}
}
class MyClass12 implements MyInterface{
public void someDifferentName(){
}
public void invoke(){
someDifferentName();
}
}
now call invoke()
method.