繁体   English   中英

在运行时切换实现

[英]switching implementation in runtime

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

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

由用户在GUI中选择实现。

那么,可以使用if-elseswitch选择实现吗?
我曾经考虑过Java反射,但我不知道如何实现它。 有什么建议么 ?

我想说,使用if-else或switch语句选择实现可能是“好的”。 更好的方法(和更多的面向对象操作)将遵循以下原则:

//////////////////////////////////
// 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是此处使用的“模式”。 实例化要使用的实现,并将对它的引用保存在需要使用它的对象中。 当用户切换方法时,实例化新方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM