Java io serialization and design mode, io serialization
BytesFor more technical expertise, please stamp:Tencent cloud blog
Serialization
What is serialization?
Serialization: Save the object status
Deserialization: Read the status of the saved object
Serialization and serialization are a mechanism provided by Java to save and restore the object state.
What is the purpose of serialization?
When saving data to a file or database
When data is uploaded and transmitted over the network through a socket
When an object is transmitted through rpc rmi
How to serialize
Implement the Serializable Interface
Implement the Externalizable Interface
SerialVersionUID function serialVersionUID it is recommended that you give a definite value, not automatically generated by the system. Otherwise, when adding or removing fields (the field type and length cannot be modified, if the versions of the classes on both sides are different, deserialization will fail.
Default serialization Mechanism
If you only want a class to implement the Serializable interface without any other processing, the default serialization mechanism is used. Using the default mechanism, when serializing an object, not only the current object itself will be serialized, but other objects referenced by this object will also be serialized. Similarly, other Objects referenced by these other objects will also be serialized, and so on. Therefore, if an object contains a member variable that is a container-class object, and the elements contained in these containers are also a container-class object, the serialization process will be complicated and costly.
(01) serialization of static and transient variables does not automatically save the status.
The role of transient is that variables declared with transient will not be automatically serialized.
(02) serialization is not supported for Socket and Thread classes. If there is a Thread member in the serialized interface, an error occurs during the serialization of this class.
This is mainly because of resource allocation. If the Socket and Thread classes can be serialized, they cannot be re-allocated after deserialization.
Example:
Package ioEx; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; import java. io. serializable; import java. util. hashMap; import java. util. iterator; import java. util. map; import java. util. map. entry; public class Serial {private static final String TMP_FILE = "text.txt"; public static void main (String [] args) {testWrite (); testRead ();} private static void testWrite () {try {ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream (TMP_FILE); AnObject box = new AnObject (1, 1, "1"); out. writeObject (box); out. writeBoolean (true); out. writeByte (byte) 65); out. writeChar ('A'); out. writeInt (0, 20160415); out. writeFloat (3.14F); out. writeDouble (Math. PI); HashMap <String, String> map = new HashMap <String, String> (); map. put ("a", "a"); map. put ("B", "B"); map. put ("c", "c"); out. writeObject (map); out. close ();} catch (Exception ex) {ex. printStackTrace () ;}} private static void testRead () {try {ObjectInputStream in = new ObjectInputStream (new FileInputStream (TMP_FILE); AnObject box = (AnObject) in. readObject (); System. out. println ("testWrite box:" + box); System. out. println ("boolean:" + in. readBoolean (); System. out. println ("byte:" + (in. readByte () & 0xff); System. out. println ("char:" + in. readChar (); System. out. println ("int:" + in. readInt (); System. out. println ("float:" + in. readFloat (); System. out. println ("double:" + in. readDouble (); // read the HashMap object HashMap <String, String> map = (HashMap <String, String>) in. readObject (); Iterator <Entry <String, String> iter = map. entrySet (). iterator (); while (iter. hasNext () {Map. entry <String, String> entry = (Entry <String, String>) iter. next (); System. out. println (entry. getKey () + "--" + entry. getValue ();} in. close ();} catch (Exception e) {e. printStackTrace () ;}} class AnObject implements Serializable {private int obja; private int objb; private String objc; private static int statica; private transient int transienda; // serialization is possible only when static or transient modification is required. Otherwise, the private static transient Thread thread = new Thread () {@ Override public void run () {System. out. println ("Serializable") ;}}; public AnObject (int obja, int objb, String objc) {this. obja = obja; this. objb = objb; this. objc = objc; this. statica = obja; this. transienda = obja;} // If You Want to serialize transient, You need to override writeObject, And the readObject method // private void writeObject (ObjectOutputStream out) throws IOException {// out. defaultWriteObject (); // out. writeInt (transienda); //} // private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {/in. defaultReadObject (); // transienda = in. readInt (); //} @ Override public String toString () {return "obja:" + obja + "," + "objb:" + objb + ", "+" objc: "+ objc +", "+" statica: "+ statica +", "+" transienda: "+ transienda ;}}
Java io Design Mode
The java io framework mainly uses two decorative and adapter modes.
Decoration mode, also known as Wrapper Mode
The decoration mode extends the object functions in a transparent way to the client. It is an alternative to the inheritance relationship.
-
In decoration mode, you can create a packaging object, that is, decoration, to enclose the actual object.
-
The decoration mode dynamically attaches more responsibilities to an object in a transparent way to the client. In other words, the client does not think that objects are different before and after decoration.
-
The decoration mode can extend the functions of objects without creating more child classes.
-
The decoration mode delegates client calls to the decorated class. The key to the decoration mode is that the extension is completely transparent.
Decoration mode role
-
Abstract Component role (Component): provides an abstract interface to standardize the objects for receiving additional responsibilities.
-
Concrete Component: defines the class to receive additional responsibilities.
-
Decorator: holds a reference to a Component object and defines an interface consistent with the abstract Component Interface.
-
Concrete Decorator: attaches an additional responsibility to the component object.
Features of the decoration Mode
-
The decoration object and the real object have the same interface. In this way, the client object can interact with the decoration object in the same way as the real object.
-
A decoration object contains a reference of a real object ).
-
The decoration object receives all requests from the client and forwards these requests to the real object.
-
Decoration objects can be added with some features before or after these requests are forwarded.
In this way, you can add additional functions externally without modifying the structure of the given object during running.
Example:
package Test;public class Wrapper { public static void main(String[] args) { Component c = new RealizeComponent(); Component c1 = new RealizeDecorator1(c); c1.say(); System.out.println("--"); Component c2 = new RealizeDecorator2(c1); c2.say(); }}interface Component{ public void say();}class RealizeComponent implements Component{ @Override public void say() { System.out.println("A"); }}class Decorator implements Component{ private Component component; public Decorator(Component component) { this.component = component; } @Override public void say(){ component.say(); }}class RealizeDecorator1 extends Decorator{ public RealizeDecorator1(Component component){ super(component); } @Override public void say(){ super.say(); this.sayAnother(); } private void sayAnother(){ System.out.println("B"); }}class RealizeDecorator2 extends Decorator{ public RealizeDecorator2(Component component){ super(component); } @Override public void say(){ super.say(); this.sayAnother(); } private void sayAnother(){ System.out.println("C"); }}
Advantages of decoration Mode
The purpose of the relationship between the decoration mode and inheritance is to expand the object functions, but the decoration mode can provide more flexibility than inheritance. The decoration mode allows the system to dynamically "Paste" a desired "decoration", or remove an unwanted "decoration ". The inheritance relationship is different. The inheritance relationship is static, which is determined before the system runs.
By using different specific decorative classes and the arrangement and combination of these decorative classes, designers can create a combination of many different behaviors.
Disadvantages of decoration Mode
Because the decorative mode is used, there are a few categories that are needed than the inheritance relationship. Use fewer classes, of course, make the design easier. However, on the other hand, the use of decoration mode will produce more objects than the use of inheritance relationships. More objects make it difficult to query errors, especially those objects look very similar.
Decoration mode in JAVA IO
Abstract Component role: played by InputStream. This is an abstract class that provides unified interfaces for various subtypes.
ConcreteComponent roles are played by ByteArrayInputStream, FileInputStream, PipedInputStream, and StringBufferInputStream. They implement the interfaces specified by the abstract component role.
Decorator: played by FilterInputStream. It implements the interface specified by InputStream.
ConcreteDecorator roles: these roles are played by several classes: BufferedInputStream, DataInputStream, and LineNumberInputStream and PushbackInputStream.
Adapter Mode
Is a class diagram of the adapter mode. The Adapter design mode has three important roles: Adaptee, Adapter, and Target object. The two existing classes to be combined are Adaptee and Target object Target roles. As shown in the class diagram, we need to create an Adapter to combine them.
Simple adapter example:
package AdapterEx;class Apple { public void getAColor(String str) { System.out.println("Apple color is: " + str); }}class Orange { public void getOColor(String str) { System.out.println("Orange color is: " + str); }}class AppleAdapter extends Apple { private Orange orange; public AppleAdapter(Orange orange) { this.orange = orange; } public void getAColor(String str) { orange.getOColor(str); } }public class AdapterEx { public static void main(String[] args) { Apple apple = new Apple(); apple.getAColor("green"); Orange orange = new Orange(); AppleAdapter aa = new AppleAdapter(orange); aa.getAColor("red"); }}
The Java I/O library uses a large number of adapter modes. For example, ByteArrayInputStream is an adapter class that inherits the InputStream interface and encapsulates a byte array. In other words, it adapts a byte array interface to an InputStream stream processor interface.
We know that Java supports four types: Java interfaces, Java classes, Java arrays, and primitive types (int, float, etc ). The first three types are reference types. The instances of classes and arrays are objects, and the values of the original type are not objects. That is, the Java array is the same as all other objects, regardless of the element type stored in the array. In this way, ByteArrayInputStream conforms to the adapter mode description and is an object-form adapter class. FileInputStream is an adapter class. FileInputStream inherits the InputStrem type and holds a reference to FileDiscriptor. This is an adapter mode that adapts a FileDiscriptor object to an InputStrem object.
Similarly, in the OutputStream type, all the original stream processors are adapter classes. ByteArrayOutputStream inherits the OutputStream type and holds a reference to the byte array. Its byte array interface is adapted to the OutputString type interface, so it is also an object-form adapter mode application.
FileOutputStream inherits the OutputStream type and holds a reference to the FileDiscriptor object. This is an object-type adapter mode that adapts the FileDiscriptor interface to the OutputStream interface form.
Reader-Type Raw stream processors are used in adapter mode. StringReader is an adapter class. The StringReader class inherits the Reader type and holds a reference to the String object. It adapts the String interface to the Reader interface.
Comparison between decoration mode and adapter Mode
(1) Decoration mode and adapter mode are designed by encapsulating other objects.
(2) The ideal decoration mode requires that the interface of the specific component role and decoration role be exactly the same as that of the abstract component role when the function of the decorated object is enhanced; the adapter mode is not. Generally, the adapter mode does not require enhancement of the functions of the source object. It only uses the functions of the source object, but changes the interfaces of the source object, to be consistent with the target interface.
(3) There are two decorative modes: transparent and translucent. the difference lies in whether the interfaces are completely consistent. The important fact about the decoration mode is that it is difficult to find the ideal decoration mode. In general, adding new behaviors will occur when the function of an object is enhanced. Therefore, it is difficult to avoid the interface width of the decorative role than that of the abstract component role, this phenomenon exists in many types of linked stream processors in the Java I/O library. The more new methods a decoration class provides, the farther it is from the pure decoration mode, and the closer it is from the adapter mode.
Link: http://blog.tingyun.com/web/article/detail/460