One day a design pattern---prototype mode __ design mode

Source: Internet
Author: User
Tags ming serialization shallow copy

Description: Specifies the type of object to create with a prototype instance, and creates a new object by copying the prototypes. This model is relatively simple, in fact, we only need to grasp the knowledge of the object copy.

Scenario: When using objects, we might create new objects in the following ways. However, this simply points the STU2 reference to the STU1 rather than creating a new object. After we have changed the properties of STU2, it will also cause stu1 changes.

Student stu2 = STU1;
first, the concept of object copy

When we implement the object copy, we should first implement the Cloneable interface and rewrite the Clone () method.

Here we have to mention the concept of object copying-that is, shallow copies and deep copies.

Shallow copy:
Copy the value of a member variable of a value type, copy only the reference to the member variable of the reference type, and do not copy the referenced object. That is, if there is a property of the object type in the copied object, its subsequent transformation will have an effect on the reference used.

Deep Copy:
A value-type member variable is copied, and a reference object's replication is also made to the member variable of the reference type. This prevents the above situation from happening. second, shallow copy

Scene: Millet bought a PSP, Xiaoming saw also let Millet help buy a. However, when Millet bought the activation of the use of their own account. Xiaoming wants to modify the username password after a period of time and increase the memory size. Memory is increased, but because of their own modified account, resulting in millet account can not be used ...

Account Number

public class Account {
    private String name;
    private String password;

    @Override public
    String toString () {return
        "acount name:" + name + ", acount name:" + password;
    }

    Setter and Getter
}

PSP

public class PSP implements cloneable {
    private String color;
    private double price;
    Private account Account;
    private int ram;

    @Override
    protected Object Clone () {
        psp PSP = null;
        try {
            psp = (PSP) Super.clone ();
        } catch (Clonenotsupportedexception e) {
            e.printstacktrace ();
        } return
        psp;
    }

    @Override public
    String toString () {return
        color + ", + Ram +", "+ Price +", "+ account;
    }
    Setter and Getter
}

Test

    public static void Main (string[] args) {
        psp PSP1 = new PSP ();
        Account ACC = new account ();
        Acc.setname ("millet");
        Acc.setpassword ("123");
        Psp1.setaccount (ACC);
        Psp1.setcolor ("Red");
        Psp1.setprice (1600.0);
        Psp1.setram (8);
        System.out.println ("Millet:" + psp1.tostring ());

        PSP PSP2 = (PSP) Psp1.clone ();
        System.out.println ("Xiao Ming:" + psp2.tostring ());

        System.out.println ("Xiaoming modifies memory and account ==========");
        Psp2.getaccount (). SetName ("Xiaoming");
        Psp2.getaccount (). SetPassword ("555");
        Psp2.setram ();
        System.out.println ("Millet:" + psp1.tostring ());
        System.out.println ("xiaoming:" + psp2.tostring ());
    }

Output

Millet: Red,8,1600.0,acount Name: Millet, acount name:123
xiaoming: Red,8,1600.0,acount name: Millet, acount name:123
xiaoming Modify memory and account = = = =======
Millet: Red,8,1600.0,acount name: xiaoming, acount name:555
xiaoming: Red,16,1600.0,acount name: xiaoming, acount name:555

As you can see, the basic attribute of a shallow copy is replication, and the object type uses the original reference (or it can be explained by looking at the hashcode of both account). third, deep copy

To achieve deep copy, we can use serialization (serialization), we can serialize the object to the stream, and then get it by deserialization, so that we can get a full copy. It should be noted here that our class needs to implement the Serializable interface, otherwise it will report an java.io.NotSerializableException exception.

Account Number

Public class Account implements Serializable {
    private static final long Serialversionuid = -7747721962690262418l;
  private String name;
    private String password;

    @Override public
    String toString () {return
        "acount name:" + name + ", acount name:" + password;
    }

    Setter and Getter
}

PSP

public class PSP implements Cloneable, Serializable {private static final long Serialversionuid = 6401635201114419015
    L
    private String color;
    private double price;
    Private account Account;

    private int ram;
        @Override protected Object Clone () {PSP PSP = null;
            try {//write the object into the stream bytearrayoutputstream bos = new Bytearrayoutputstream ();
            ObjectOutputStream Oos;
            Oos = new ObjectOutputStream (BOS);

            Oos.writeobject (this);
            Read it back from the stream bytearrayinputstream bis = new Bytearrayinputstream (Bos.tobytearray ());
            ObjectInputStream ois = new ObjectInputStream (bis);
        PSP = (PSP) Ois.readobject (); catch (IOException |
        ClassNotFoundException e) {e.printstacktrace ();
    Return to PSP;
    @Override public String toString () {return color + ", + Ram +", "+ Price +", "+ account; }//Setter and GettER} 

Test

    public static void Main (string[] args) {
        psp PSP1 = new PSP ();
        Account ACC = new account ();
        Acc.setname ("millet");
        Acc.setpassword ("123");
        Psp1.setaccount (ACC);
        Psp1.setcolor ("Red");
        Psp1.setprice (1600.0);
        Psp1.setram (8);
        System.out.println ("Millet:" + psp1.tostring ());

        PSP PSP2 = (PSP) Psp1.clone ();
        System.out.println ("Xiao Ming:" + psp2.tostring ());

        System.out.println ("Xiaoming modifies memory and account ==========");
        Psp2.getaccount (). SetName ("Xiaoming");
        Psp2.getaccount (). SetPassword ("555");
        Psp2.setram ();
        System.out.println ("Millet:" + psp1.tostring ());
        System.out.println ("xiaoming:" + psp2.tostring ());
    }

Output

Millet: Red,8,1600.0,acount Name: Millet, acount name:123
xiaoming: Red,8,1600.0,acount name: Millet, acount name:123
xiaoming Modify memory and account = = = =======
Millet: Red,8,1600.0,acount name: Millet, acount name:123
Xiao Ming: red,16,1600.0,acount name: xiaoming, acount name:555

Can see, such as Xiao Ming to modify the account number, Xiao Ming's account password will not be modified, so as to avoid this situation above.

more patterns: one day a design pattern-classification and six major principles

more Source: Https://github.com/oDevilo/Java-Base

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.