I have the following class
class Message{
private List content;
private String messageType;
public Message(String messageType, List content){
this.content = content;
this.messageType = messageType;
}
}
Okey, now imagine i want to send different message types. For example, the message type "friends". I want to store their ID number ( int
for example) as a key to find their names ( String
). That reminds me that i should use the HashMap
class. Or a simple String
, whatever. And other more cases where i need to use other object types.
The main question here is: how i should proceed here to code a class that have two attributes:
I have read that casting is a bad practice, so i dont want to declare content
as an object and then, cast it in function of the message type.
My thoughts:
getContent()
in Message
class, i need to stablish the data type that it returns, what get me back to the main issue. This way get useless since i need to send the Message
and not the subclass. You don't need messageType
at all, you can just define a generic type with class and use it in content
, eg:
class Message<T> {
private List<T> content;
public Message(List<T> content){
this.content = content;
}
}
Now, let's say if the type is String
, you can do:
Message<String> message = new Message<>(new ArrayList<String>());
This way, you can instantiate Message
class with different types. Here is the documentation on generic class types.
class Message{
private List content;
private HashMap<String,Integer> messageType = new HashMap<String,Integer>();
public Message(HashMap messageType, List content){
this.content = content;
this.messageType = messageType;
}
}
Does this code make sense???
You can have an interface that contains the common methods that apply to all message types and the have all the messages implement the Sendable interface.
interface Sendable {
public String getContent();
public MessageType getMessageType();
}
public FriendMessage implements Sendable {
private String title;
private Map friends;
private messageType = MessageType.Friends;
public String getContent(){
return title+ friends.toString();
}
public MessageType getMessageType() {
return this.messageType;
}
}
public Enum MessageType {
Friends, NoFriends, Lonely
}
You should also have an Enum that will classify all your message types. This will allow you to determine the message type without having to do instanceof
or string comparison.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.