【问题标题】:generic class for static variables静态变量的泛型类
【发布时间】:2015-08-31 19:31:50
【问题描述】:

我正在尝试为下面的代码编写更通用的类,以便最终开发人员可以更改在 EvenTypes 中定义的类型和静态变量,并为他们提供在 EventType 中添加或删除静态变量的选项。

我还想为事件类型提供通用枚举,如下所示。

public interface EventType<T extends Enum<T>>
{
    String name();

    String getFriendlyName();

    Class<T> getDeclaringClass();

    T getRaw();

    public String getFullClassName();
}

原码

    public class Event implements Serializable
    {

        private String eventId;
        private String eventType;
            .....

}

public class EventTypes
{// below static variables can be changed by the developer based on requirements
    public static final String DO_FILE_CONVERSION = "100";
    public static final String DO_REMOVE_FILE = "101";
    public static final String DO_COPY_FILE = "102";
    .....

    }


public class EventProcessorFactory
    {

        @SuppressWarnings("rawtypes")
        public IEventProcessor createProcessor(EventType eventType)
                throws EventException
        {
            String eventProcessorClassName = (getEvenClassName  based on type from properties files);
            Class eventProcessorClazz = Class.forName(eventProcessorClassName);
return (IEventProcessor) eventProcessorClazz.newInstance();
            }
    }

properties.file
----
100=FileConversion.class
101=FileRemove.class
102= FileCopy.class

【问题讨论】:

  • 为什么?这里有什么好处?你失去了类型安全,你增加了复杂性,很容易犯错误,并且要更改属性文件,无论如何你都需要添加代码。为什么??
  • 原因是那些静态变量应该由最终开发人员添加。我只想提供接口
  • 你为什么不把EventTypes 变成enum? (public enum EventTypes implements EventType。

标签: java enums


【解决方案1】:

使 Event 成为一个接口并从 Serializable 扩展它。

然后使用枚举来实现该事件接口。示例:

public interface Event extends Serializable {
     // Throw in your methods here
}

public enum MyEvents implements Event {
    DO_FILE_CONVERSION, DO_REMOVE_FILE, DO_COPY_FILE;
    // Implement methods
}

这样,您的接口(即您希望 Event 能够执行的任何操作)与实现(存在哪些事件以及它们的实现)分开。

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 2012-01-02
    • 2017-12-29
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多