Global function or function with no name java for factory pattern

309 views Asked by At

I want to declare a factory class with some methods and attributes that can be used like this:

ClassFactory myObj = MyObj("Class1").method1("input 2");

It seems that this is not a valid JAVA statement because JAVA is fully Object oriented and don't let to declare global function. But if there are a mechanism that let define function without name we can define it as a static function and use it as mentioned above.

Is there any way to implement that in JAVA in that manner or any other way?

2

There are 2 answers

0
mhbashari On BEST ANSWER

Thanks to Sotirios Delimanolis for Help: this is possible with defining the static method and import it statically in every where you want.

package factorypakcage;

public class firstFactory{
    public static factoryFunction(String className){
        //switch case for class creation
    }
}

Using like this

import static factorypakcage.firstFactory.factoryFunction;
...
MyClass MyObj = factoryFunction("Class Name");
0
astryk On

You can create a public static method in a class and it can be use globally. For instance a method public static boolean doesWork() { return true; } in a public class named GlobalClass can be accessed by GlobalClass.doesWork() and would return true.