gpt4 book ai didi

java - 运行时切换实现

转载 作者:行者123 更新时间:2023-12-01 14:29:01 24 4
gpt4 key购买 nike

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

  • 使用序列化
  • 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com