Sha
Sha

Reputation: 1191

How Can I Create method In Java With Same Type Parameter?

My code looks like below:

enum EnumType {
 CATEGORY,
 GROUP,
 MAIN
}

Methods:

public void call(EnumType type){
   switch(type):
     case CATEGORY:
        return methodForCategory();
     case GROUP:
        return methodForGroup();
     ...
}
public void methodForCategory(){
   ... Operations according to EnumType.CATEGORY
}
public void methodForGroup(){
   ... Operations according to EnumType.GROUP
}
public void methodForMain(){
   ... Operations according to EnumType.MAIN
}

But I want to call it without switch/case like below;

public void call(EnumType type){
    methodForType(EnumType type);
}

Is it possible or is there any better alternative?

Upvotes: 4

Views: 147

Answers (2)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You can use an EnumMap as a registry of methods and using the Enum supplied you can return the correct implementation of the Runnable. I have used Runnable as a functional interface as it takes no inputs and produces no output.

In another class where you have the business logic, you can initialize the map and add the corresponding Runnable implementation:

class Strategy{

    private final EnumMap<EnumType, Runnable> map;

    public Strategy(){
        //Initialize values here
        map = new EnumMap<>(EnumType.class);
        map.put(EnumType.CATEGORY, () -> {
            System.out.println("CATEGORY");
        });
        map.put(EnumType.GROUP, () -> {
            System.out.println("GROUP");
        });
        map.put(EnumType.MAIN, () -> {
            System.out.println("MAIN");
        });
    }

    public void call(EnumType type){
        map.get(type).run();
    }
}

Then you can invoke the call() method by supplying the type of Enum as a parameter:

public static void main(String args[]){
    Strategy str = new Strategy();
    str.call(EnumType.CATEGORY);
    str.call(EnumType.GROUP);
    str.call(EnumType.MAIN);
}

Upvotes: 1

Gaurav Jeswani
Gaurav Jeswani

Reputation: 4592

You can create the method implementation inside the enum as below:

public enum EnumType {

  CATEGORY {

    @Override
    public void processMethod() {
      // Do something here
    }

  },
GROUP {

    @Override
    public void processMethod() {
      // Do something here
    }

  },
MAIN {

    @Override
    public void processMethod() {
      // Do something here
    }

  };

public abstract void processMethod();
}

And update call method implementation as:

public void call(EnumType type){
   type.processMethod();
}

And switch code should not return anything as method return type is void.

Upvotes: 5

Related Questions