Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

java - execute good method at runtime

I created a class Message with several Inheritances (UserMessage extends Message, BotMessage extends Message, ...)

In a service class BotService I have the following methods:

private void dealWithMessage(Message message) {
    loadMessage(message);
}

private void loadMessage(UserMessage message) {
    LOGGER.info("it's a user message");
}

private void loadMessage(BotMessage message) {
     LOGGER.info("it's a bot message");
}

private void loadMessage(Message message) {
     LOGGER.info("I do not expect to go here");
}

I do not want to add loadMessage() method in UserMessage and BotMessage classes. How can I acheive to go in specific loadMessage methods at runtime please (for the moment it always go in the last method with Message class parameter)? Should I use generic type in some way ?

thank you

question from:https://stackoverflow.com/questions/65936438/execute-good-method-at-runtime

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the Visitor pattern:

interface MessageVisitor {
  void visitUserMessage(UserMessage message);
  void visitBotMessage(BotMessage message);
}

Then add to your Message interface:

...
void accept(MessageVisitor visitor);
...

Which is implemented as:

class UserMessage implements Message {
...
void accept(MessageVisitor visitor) {
   visitor.visitUserMessage(this);
}

and

class BotMessage implements Message {
...
void accept(MessageVisitor visitor) {
   visitor.visitBotMessage(this);
}

so loadMessage looks like:

MessageVisitor visitor = new MessageVisitor() {
   void visitUserMessage(UserMessage message) {
      LOGGER.info("it's a user message");
   }
      void visitBotMessage(UserMessage message) {
      LOGGER.info("it's a bot message");
   }
}

message.accept(visitor);

The nice thing about this is that if you create a new class which implements Message you are forced to implement accept, which will prompt you to add a new method to MessageVisitor, and so add its implementation to all MessageVisitor implementations. Using instanceof allows you to forget to add new cases to your code when new classes are introduced.

It also keeps your business logic separate from your Message classes -- they just implement the mechanism of the visitor pattern, not any actual functionality.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...