Home > Back-end >  Static method in products created by factory
Static method in products created by factory

Time:10-11

I have a factory that creates different types of products:

public class Factory {
    public Product createProduct(String type) {
        if(type.equals("Product1")) {
            return new Product1();
        }
        else if(type.equals("Product2")) {
            return new Product2();
        }
    }
}

The product classes look like this:

public abstract class Product {
    public static doSomething() {
        //...
    }
}

public class Product1 extends Product {
    //...
}

public class Product2 extends Product {
    //...
}

Depending on a String value I'd like to call doSomething() on the corresponding class. How can I call doSomething() on the corresponding class without creating an instance of it? Is there a better way than creating if-else statements as shown below?

if(type.equals("Product1")) {
    //call doSomething() on Product1 class
}
else if(type.equals("Product2")) {
    //call doSomething() on Product2 class
}

CodePudding user response:

My idea is to use reflection:

Factory factory = new Factory();

Product product = factory.createProduct("Product1");

try{
    
    //get the method `doSomething` from product reference.
    Method doSomethingMethod = product.getClass().getMethod("doSomething");

    //invoke the method from product reference
    doSomethingMethod.invoke(product);

catch(Exception e){ 
    e.printStackTrace(); 
}

But my question is why you don't directly call Product.doSomething()?

Because this method is static that means you can't override it in subclasses.

CodePudding user response:

You can't call doSomething on your subclasses without instantiating them, I mean you can but there will be no difference between product1 and product2 because you are you are going to call the doSomething of the abstract class product because you can't override a static method, you could make the doSomething method of product non-static so that you could override it and have different implementation of it in different subclasses like you want without even checking the type, but then you'd have to instantiate the objects on which you want to call the method, so I suggest not defining the doSomething method in product and just add a "personal" static one to each subclass, as so that you could still assign every product subclass to a product variable like a list and call the method, but then again it would make no sense because why wanting to make the method static so that you don't have to instantiate stuff and then still instantiate them on a list? And why having a factory class whose purpose is exactly to instantiate objects if you want to call doSomething without instantiating? Confusing. it'd be easier if you removed the factory or made doSomething non-static and finally instantiate stuff. I'm tired of writing instantiate, ugh, ugly and complicated word.

  • Related