Java策略模式应用实战

时间:2024-11-19 19:31:57

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
    }
}

相关文章