Search code examples
javaoopfactory-pattern

Global function or function with no name java for factory pattern


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?


Solution

  • 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");