反射+配置文件+抽象工厂模式

反射+配置文件+抽象工厂模式

优化方案

为了进一步优化代码,我们可以将产品类型与类名的映射关系存储在配置文件中,使得系统更易于管理和扩展。以下是在上述代码基础上添加配置文件的优化示例:

1.配置文件(shape_mapping.properties)

circle=com.example.Circle
square=com.example.Square

2.定义产品接口及其实现(保持不变

public interface Shape {
    void draw();
}
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle.");
    }
}
public class Square implements Shape {
    @Override
    public 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);
        }
    }

    @Override
    public 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();
    }
}

在这个优化后的示例中,我们将产品类型与类名的映射关系存储在配置文件中。当需要添加、修改或删除形状类型时,只需编辑配置文件,无需修改源代码。这样极大地提高了系统的可维护性和可扩展性。

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值