public interface Message extends Cloneable{
/*
* 信息都是可以被发送的
*/
public void send(String content);
public String getContent();
public Object clone();
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class LoveMessage implements Message,Serializable {
private String content;
public void send(String content) {
this.content = content;
}
@Override
public Object clone() {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo;
InputStream bi;
ObjectInputStream oi = null;
Object target = null;
try {
oo = new ObjectOutputStream(bo);
oo.writeObject(this);
bi = new ByteArrayInputStream(bo.toByteArray());
oi = new ObjectInputStream(bi);
target = oi.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return target;
}
public String getContent() {
return this.content;
}
}
import java.util.Vector;
public class MessageManager {
public Vector<Message> messages = new Vector<Message>();
public void add(Message message){
messages.add(message);
}
public Message getClone(int index){
Message message = messages.get(index);
if( message != null){
return (Message) message.clone();
}
return null;
}
}
public class Client {
public static void init(MessageManager mgr){
Message m1 = new LoveMessage();
m1.send("我爱你,你却爱着他");
mgr.add(m1);
Message m2 = new LoveMessage();
m2.send("ILOVEYOU");
mgr.add(m2);
}
public static void main(String[] args){
MessageManager mgr = new MessageManager();
init(mgr);//初始化
System.out.println(mgr.getClone(1).getContent());
}
}