/** * 数据序列化接口 * * @author Administrator * */ public interface IDataMarshaller { /** * 序列化 * * @param data 数据对象,不可以为空 * @param out 序列化目标,不可以为空 * @param additional 额外附属信息,如果没有用,可以为空 */ void marshal(Object data, OutputStream out, Object additional) throws Exception; /** * 反序列化 * * @param in 输入,不可以为空 * @param additional 额外附属信息,如果没有用,可以为空 * @return 数据对象 */ <T> T unmarshal(InputStream in, Object additional) throws Exception; } /** * 数据序列化工厂 * * @author Administrator * */ public class DataMarshallerFactory { public static IDataMarshaller getDataMarshaller() { return new JdkDataMarshaller(); } } /** * 抽象基类 * * @author Administrator * */ public abstract class AbstractDataMarshaller implements IDataMarshaller { public void marshal(Object data, OutputStream out, Object additional) throws Exception { if (data == null) { throw new IllegalArgumentException("Data is null!"); } if (out == null) { throw new IllegalArgumentException("OutputStream is null!"); } doMarshal(data, out, additional); } public <T> T unmarshal(InputStream in, Object additional) throws Exception{ if (in == null) { throw new IllegalArgumentException("InputStream is null!"); } return doUnmarshal(in, additional); } protected abstract void doMarshal(Object data, OutputStream out, Object additional) throws Exception; protected abstract <T> T doUnmarshal(InputStream in, Object additional) throws Exception; } /** * 使用JDK的序列化,反序列化机制实现的数据序列化 * * @author Administrator * */ public class JdkDataMarshaller extends AbstractDataMarshaller { @Override protected void doMarshal(Object data, OutputStream out, Object additional) throws Exception { ObjectOutputStream outObj = out instanceof ObjectOutputStream ? (ObjectOutputStream)out : new ObjectOutputStream(out); outObj.writeObject(data); } @SuppressWarnings("unchecked") @Override protected <T> T doUnmarshal(InputStream in, Object additional) throws Exception { ObjectInputStream objIn = in instanceof ObjectInputStream ? (ObjectInputStream)in : new ObjectInputStream(in); return (T)objIn.readObject(); } } /** * 使用XStream的序列化实现 * * @author Administrator * */ public class XStreamDataMarshaller extends AbstractDataMarshaller { private XStream xstream = new XStream(new DomDriver("UTF-8")); @Override protected void doMarshal(Object data, OutputStream out, Object additional) throws Exception { xstream.toXML(data, out); } @SuppressWarnings("unchecked") @Override protected <T> T doUnmarshal(InputStream in, Object additional) throws Exception { return (T)xstream.fromXML(in); } }