工厂模式的优化--增加反射或配置文件

参考:反射例子

内容

  • 工厂模式
  • 增加反射来提高灵活性
  • 增加配置文件进一步优化

代码实现

实体类

public interface ISleep {
    String sleep();
}

public class CatSleep implements ISleep {
    @Override
    public String sleep() {
        return "cat xiaohu  is sleeping!";
    }
}

public class DogSleep implements ISleep {
    @Override
    public String sleep() {
        return "dog qiqi is sleeping!";
    }
}

基本的抽象工厂

/**
 *  简单工厂
 */
public class NormalFactory {
    public static ISleep getSleepObject(String tag) throws IllegalArgumentException{
        if (TextUtils.equals(tag,"cat")){
            return new CatSleep();
        }else if (TextUtils.equals(tag,"dog")){
            return new DogSleep();
        }else {
            throw new IllegalArgumentException("wrong argument!");
        }
    }
}

增加反射来优化

/**
 * 利用反射来优化
 */
public class ReflectFactory {

    public static ISleep getSleepObject(String className) throws IllegalArgumentException{

        ISleep iSleep = null;
        try {
            iSleep =(ISleep) Class.forName(className).newInstance();
        }catch (Exception e){
            throw new IllegalArgumentException("wrong class name");
        }
        
        return iSleep;
    }
}

增加配置文件来优化(读取本地文件等,这里模拟下)

/**
 *  从配置文件读取: 这里简单模拟下
 */
public class ConfigFactory {

    private static HashMap map;

    public static String path = "com.pq.toolslibrary.factoryOptimize.interfaces.";

    static {
        map = new HashMap<>();
        map.put("cat",path+"CatSleep");
        map.put("dog",path+"DogSleep");
    }


    public static ISleep getSleepObject(String tag) throws IllegalArgumentException{

        ISleep iSleep = null;

        try {
            iSleep =(ISleep) Class.forName(map.get(tag)).newInstance();
        }catch (Exception e){
            throw new IllegalArgumentException("wrong class name");
        }


        return iSleep;
    }
}

使用:

public class FactoryUtil {

    public static String demo(){
        StringBuilder stringBuilder = new StringBuilder("工厂模式的优化:").append("\n");
        stringBuilder.append("优化前: ").append("\n")
                .append(NormalFactory.getSleepObject("cat").sleep()).append("\n")

                .append("反射优化").append("\n")
                .append(ReflectFactory.getSleepObject(ConfigFactory.path+"DogSleep").sleep()).append("\n")

                .append("配置优化").append("\n")
                .append(ConfigFactory.getSleepObject("dog").sleep());

        return stringBuilder.toString();
    }
}

你可能感兴趣的:(工厂模式的优化--增加反射或配置文件)