当前位置: 首页 > article >正文

Java策略模式应用实战

Java策略模式应用实战

推送内容并预检

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

// DTO class
class DataDTO {
    private String type;
    private String field1;
    private String field2;
    // Other fields...

    // Getters and Setters
    public String getType() { return type; }
    public void setType(String type) { this.type = type; }
    public String getField1() { return field1; }
    public void setField1(String field1) { this.field1 = field1; }
    public String getField2() { return field2; }
    public void setField2(String field2) { this.field2 = field2; }
}

// Define an interface for the push service
interface PushService {
    void push(DataDTO dto);
    boolean preCheck(DataDTO dto);
}

// Implementation for TypeA
class TypeAPushService implements PushService {
    @Override
    public void push(DataDTO dto) {
        // Logic to push data for TypeA
        Logger.getLogger(TypeAPushService.class.getName()).log(Level.INFO, "Pushing data for TypeA: {0}", dto);
    }

    @Override
    public boolean preCheck(DataDTO dto) {
        // Check required fields for TypeA
        return PreCheckUtil.commonPreCheck(dto, DTOType1.class);
    }
}

// Implementation for TypeB
class TypeBPushService implements PushService {
    @Override
    public void push(DataDTO dto) {
        // Logic to push data for TypeB
        Logger.getLogger(TypeBPushService.class.getName()).log(Level.INFO, "Pushing data for TypeB: {0}", dto);
    }

    @Override
    public boolean preCheck(DataDTO dto) {
        // Check required fields for TypeB
        return PreCheckUtil.commonPreCheck(dto, DTOType2.class);
    }
}

// Utility method for common pre-check logic
class PreCheckUtil {
    private static final Logger LOGGER = Logger.getLogger(PreCheckUtil.class.getName());

    public static <T> boolean commonPreCheck(DataDTO dto, Class<T> requiredFieldsClass) {
        try {
            Field[] fields = requiredFieldsClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Field dtoField;
                try {
                    dtoField = dto.getClass().getDeclaredField(field.getName());
                } catch (NoSuchFieldException e) {
                    continue; // Skip fields that do not exist in DataDTO
                }
                dtoField.setAccessible(true);
                Object value = dtoField.get(dto);
                if (value == null) {
                    return false;
                }
            }
        } catch (IllegalAccessException e) {
            LOGGER.log(Level.SEVERE, "Error during pre-check: {0}", e.getMessage());
            return false;
        }
        return true;
    }
}

// DTOType1 class representing required fields for TypeA
class DTOType1 {
    private String field1;
    // Other required fields for TypeA...
}

// DTOType2 class representing required fields for TypeB
class DTOType2 {
    private String field2;
    // Other required fields for TypeB...
}

// Context class to manage different PushServices
class PushServiceContext {
    private static final Logger LOGGER = Logger.getLogger(PushServiceContext.class.getName());
    private final Map<String, PushService> serviceMap = new HashMap<>();

    public void registerService(String type, PushService service) {
        serviceMap.put(type, service);
    }

    public void pushData(DataDTO dto) {
        PushService service = serviceMap.get(dto.getType());
        if (service == null) {
            LOGGER.log(Level.SEVERE, "No PushService found for type: {0}", dto.getType());
            return;
        }
        if (service.preCheck(dto)) {
            service.push(dto);
        } else {
            LOGGER.log(Level.WARNING, "Pre-check failed for type: {0}, skipping push.", dto.getType());
        }
    }
}

// Main class to demonstrate the functionality
public class PushDataDemo {
    public static void main(String[] args) {
        // Initialize context and register services
        PushServiceContext context = new PushServiceContext();
        context.registerService("TypeA", new TypeAPushService());
        context.registerService("TypeB", new TypeBPushService());

        // Create DTOs and push data
        DataDTO dtoA = new DataDTO();
        dtoA.setType("TypeA");
        dtoA.setField1("Value1");
        context.pushData(dtoA); // Should push successfully

        DataDTO dtoB = new DataDTO();
        dtoB.setType("TypeB");
        // dtoB.setField2("Value2"); // Field2 is required for TypeB, but it's missing
        context.pushData(dtoB); // Should skip due to failed pre-check
    }
}


http://www.kler.cn/a/401494.html

相关文章:

  • Pytest-Bdd-Playwright 系列教程(10):配置功能文件路径 优化场景定义
  • 进程-系统性能和计划任务常用命令-下篇
  • 【Pythonr入门第二讲】你好,世界
  • 智能指针原理、使用和实现——C++11新特性(三)
  • Python中的with语句
  • Tomcat启动过程中cmd窗口(控制台)中文乱码的问题
  • 优化 MFC CGridCtrl 的表格布局与功能
  • C语言练习.switch
  • 竞赛思享会 | 2024年第十届数维杯国际数学建模挑战赛D题【代码+演示】
  • 使用OpenFeign+Eureka实现HTTP调用的简单示例
  • 安全平行切面的概念以及对安全行业影响
  • 前端记录3
  • 静态成员的详细讲解
  • Spark RDD 的 combineByKey、cogroup 和 compute 算子的作用
  • 第8章硬件维护-8.2 可维护性和可靠性验收
  • 抽象java入门1.5.3.2——类的进阶(中)
  • 嵌入式C语言
  • 填写工单流程
  • CTF练习4
  • TDSQL 免密码登录
  • Openstack15--块存储服务(Cinder)安装
  • SpringCloud详解
  • 阿里云SSL证书每三个月过期续期方法 —— 使用httpsok工具轻松自动续期
  • 机器学习笔记 // 天气预报、股票价格以及历史轨迹(如摩尔定律)// 时间序列的常见属性
  • 如何在Linux系统实现屏幕旋转?触觉智能RK3568鸿蒙开发板演示
  • JavaSE(十四)——文件操作和IO