反射+配置文件+抽象工厂模式
文章目录
- 反射+配置文件+抽象工厂模式
- 优化方案
优化方案
为了进一步优化代码,我们可以将产品类型与类名的映射关系存储在配置文件中,使得系统更易于管理和扩展。以下是在上述代码基础上添加配置文件的优化示例:
1.配置文件(shape_mapping.properties)
circle=com.example.Circle
square=com.example.Square
2.定义产品接口及其实现(保持不变
public interface Shape {void draw();
}
public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a circle.");}
}
public class Square implements Shape {@Overridepublic void draw() {System.out.println("Drawing a square.");}
}
3.定义抽象工厂接口
public interface ShapeFactory {Shape createShape(String shapeType);
}
4.实现抽象工厂接口
实现抽象工厂接口,利用反射和配置文件创建具体的产品对象。这里使用 java.util.Properties 类来加载配置文件。
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;public class ConfigurableShapeFactory implements ShapeFactory {private static final String CONFIG_FILE = "shape_mapping.properties";private static final Properties SHAPE_MAPPING = loadShapeMapping();private static Properties loadShapeMapping() {Properties properties = new Properties();try {properties.load(ConfigurableShapeFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE));return properties;} catch (IOException e) {throw new RuntimeException("Failed to load shape mapping configuration file: " + CONFIG_FILE, e);}}@Overridepublic Shape createShape(String shapeType) {try {// 获取对应类名的Class对象Class<?> clazz = Class.forName(SHAPE_MAPPING.getProperty(shapeType));// 获取无参构造器并创建对象Constructor<?> constructor = clazz.getDeclaredConstructor();constructor.setAccessible(true);return (Shape) constructor.newInstance();} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException |InstantiationException | InvocationTargetException e) {throw new RuntimeException("Failed to create shape: " + shapeType, e);}}
}
5.客户端代码
在客户端代码中,通过抽象工厂接口创建所需的产品,传入产品类型字符串。
public class Client {public static void main(String[] args) {// 创建一个具体工厂实例ShapeFactory factory = new ConfigurableShapeFactory();// 使用工厂创建产品并进行操作Shape circle = factory.createShape("circle");circle.draw();Shape square = factory.createShape("square");square.draw();}
}
在这个优化后的示例中,我们将产品类型与类名的映射关系存储在配置文件中。当需要添加、修改或删除形状类型时,只需编辑配置文件,无需修改源代码。这样极大地提高了系统的可维护性和可扩展性。