工厂模式+策略模式的使用

项目中会有这样的情形,通过某个参数进入不同的if分支,但是if分支太多就会导致项目难以维护,可读性也会降低,如下情形:

public class Test {
    public static void main(String[] args) {
        String ani = "pig";
        if(ani.equals("cat")){
            showCat();
        }else if(ani.equals("dog")){
            showDog();
        }
        
    }

    private static void showCat() {
        System.out.println("this is cat!");
    }

    private static void showDog() {
        System.out.println("this is dog!");
    }
}

上面情况为了方便只写了两个if的情况,假设if有十个,这时候是时候引入策略模式了

public interface Operate {
    void show();
}

不同的分支实现该策略接口

public class CatShow implements Operate {
    @Override
    public void show() {
        System.out.println("this is cat!");
    }
}
public class DogShow implements Operate {
    @Override
    public void show() {
        System.out.println("this is dog!");
    }
}

使用工厂模式生成不同的策略

public class ShowFactory {

    public static final String DOG = "dog";
    public static final String CAT = "cat";

    private static ShowFactory factory = new ShowFactory();

    private ShowFactory(){
    }

    private static Map strategyMap = new HashMap<>();
    static{
        strategyMap.put(DOG, new DogShow());
        strategyMap.put(CAT, new CatShow());
    }
    public Operate creator(String animal){
        return strategyMap.get(animal);
    }
    public static ShowFactory getInstance(){
        return factory;
    }
}
public static void main(String[] args) {
        String ani = "dog";
        Operate creator = ShowFactory.getInstance().creator(ani);
        creator.show();
}

打印结果和if else的代码一样

你可能感兴趣的:(工厂模式+策略模式的使用)