Policy Mode + Factory Method to Eliminate if...else

Keywords: Java

Today, let's talk about how to eliminate redundant if...else through strategy mode and factory method. What is the specific strategy mode, you can learn by yourself, and I will not introduce too much here.

Note: If the business scenario is simple, it is recommended to use if...else, because the code logic is simple and easy to understand.

Policy interface

Eat.java

/**
 * Policy interface
 *
 */
public interface Eat {
    
    public void eatFruit(String fruit);
    
}

Policy class

EatApple.java

/**
 * Specific strategies: eating apples
 */
public class EatApple implements Eat{
    
    @Override
    public void eatFruit(String fruit) {
        System.out.println("Eating apples");
    }

}

EatBanana.java

/**
 * Specific strategies: eating bananas
 */
public class EatBanana implements Eat {

    @Override
    public void eatFruit(String fruit) {
        System.out.println("Eat bananas");
    }

}

EatPear.java

/**
 * Specific Strategies: Eating Pears
 */
public class EatPear implements Eat {

    @Override
    public void eatFruit(String fruit) {
        System.out.println("Eat pear");
    }

}

Policy context

EatContext.java

/**
 * Policy context
 */
public class EatContext {

    private Eat eat;

    public EatContext(Eat eat) {
        this.eat = eat;
    }
    
    public void eatContext(String fruit) {
        eat.eatFruit(fruit);
    }
    
}

Policy Factory Class

EatFactory.java

/**
 * Policy Factory Class
 */
public class EatFactory {

    private static Map<String, Eat> map = new HashMap<>();
    
    static {
        map.put("apple", new EatApple());
        map.put("banana", new EatBanana());
        map.put("pear", new EatPear());
    }
    
    public static Eat getEatStrategy(String fruitType) {
        return map.get(fruitType);
    }
}

test

public class Demo {

    public static void main(String[] args) {
        String fruit = "apple";
        // Introduce specific fruit types and get Apple strategy interface
        Eat eat = EatFactory.getEatStrategy(fruit);
        // Call specific policy methods
        eat.eatFruit(fruit);
    }
}

Test results:

Eating apples

The first time to write a blog, write bad places, but also hope you leave a message for advice!

Posted by amir on Thu, 03 Oct 2019 15:05:29 -0700