mardi 28 septembre 2021

Do I need to return an object of all the concrete classes implementing an interface if I am using Factory Pattern in Java

While reviewing the code for one of my colleagues, I pointed out some code structuring improvements and how we should use Factory Design Pattern for our use-case but I have not been able to convince him so I am seeking help from the almighty community here whose opinion no developer would neglect :)

The code is structured similar to the below -

abstract class X {
    abstract y();
}

class a extends X {
    y();
}

class b extends X {
    y(){
       factory().y();
    }
}

class factory(){
    determineClass(input){
        if(input == 'a')
           return new a();
        else return null;
    }

}

I have two questions -

  1. Given that both class a, b extend class x and we are using factory class to determine which object to create, should it not ideally have an extra condition for when input == 'b' and we return new b() ?
  2. I don't think class b should extend x because it seems as if we are using this to determine which object to create and call method y() on that class. I think this should be a high level class which calls factory and not an extension of X

Aucun commentaire:

Enregistrer un commentaire