java - 运行时切换实现

标签 java reflection runtime

我正在编写简单的聊天系统。通信应该有两种实现方式:

  • 使用序列化
  • XML(自己的协议(protocol))。

实现由用户在 GUI 中选择。

那么,可以使用 if-elseswitch 来选择实现吗?
我想过Java Reflection,但我不知道如何实现它。 有什么建议 ?

最佳答案

我想说使用 if-else 或 switch 语句来选择实现是“可以的”。更好的(并且更多的 OOP)方法应该是这样的:

//////////////////////////////////
// The communication interfaces
//////////////////////////////////

public interface IChatCommunicationFactory {
    public String toString();
    public IChatCommunication create();
}

public interface IChatCommunication {
    public sendChatLine(String chatLine);
    public registerChatLineReceiver(IChatLineReceiver chatLineReceiver);
}

public interface IChatLineReceiver {
    public void onChatLineReceived(String chatLine);
}

//////////////////////////////////
// The communication interface implementations
//////////////////////////////////

public class XMLChatCommunicationFactory implements IChatCommunicationFactory {
    public String toString() {
        return "XML implementation";
    }

    public IChatCommunication create() {
        return new XMLChatCommunication();
    }
}

public class XMLChatCommunication implements IChatCommunication {
    private XMLProtocolSocket socket;

    public XMLChatCommunication() {
        // set up socket
    }

    public sendChatLine(String chatLine) {
        // send your chat line
    }

    public registerChatLineReceiver(IChatLineReceiver chatLineReceiver) {
        // start thread in which received chat lines are handled and then passed to the onChatLineReceived of the IChatLineReceiver
    }
}

// Do the same as above for the Serialization implementation.


//////////////////////////////////
// The user interface
//////////////////////////////////

public void fillListBoxWithCommuncationImplementations(ListBox listBox) {
    listBox.addItem(new XMLChatCommunicationFactory());
    listBox.addItem(new SerializationChatCommunicationFactory());
}

public IChatCommunication getChatCommunicationImplementationByUserSelection(ListBox listBox) {
    if (listBox.selectedItem == null)
        return null;

    IChatCommunicationFactory factory = (IChatCommunicationFactory)listBox.selectedItem;
    return factory.create();
}

您可以更进一步,实现类似 ChatCommunicationFactoryRegistry 的功能,其中注册每个 IChatCommunicationFactory。这将有助于将“业务”逻辑移出用户界面,因为 fillListBoxWithCommuncationImplementations() 方法只需要了解注册表,而不再需要了解各个实现。

关于java - 运行时切换实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16964070/

相关文章:

java - 为什么我应该使用 Runnable 而不是 Thread?

java - 如何解决ClassNotFoundException引起的NoClassDefFoundError?

java - 从基于 Java 的 Web 应用程序发送预定电子邮件的最佳方式是什么?

java - 以编程方式停止 Tomcat 中的 servlet

java.lang.NoClassDefFoundError : Could not initialize class XXX

visual-studio-2010 - MS缺少VSTO 4.0 Runtime下载?

java - 比较几个 javabean 属性的最佳方法是什么?

java - 使用反射加载 Build.getRadioVersion() 时出现 NoSuchMethodException

c# - 获取继承类型列表并不适用于所有类型

java - Runtime.getRuntime().exec() 和双击执行批处理文件有什么区别?