Prototype patterns of Java design patterns

Source: Internet
Author: User
Tags shallow copy

1. First: Let's start by introducing what cloning is!

Clones are also called copies: copies can be divided into: 1. Shallow copy 2. Deep copy.






PackageChenyang;ImportJava.util.*;/** * * @author65245 * To achieve cloning*/ Public classPersonImplementscloneable{PrivateString name; Private intAge ; PrivateString sex; PrivateList<string>friends; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicString Getsex () {returnsex; } Public voidsetsex (String sex) { This. Sex =sex; } PublicList<string>getfriends () {returnfriends; } Public voidSetfriends (list<string>friends) { This. Friends =friends; } PublicPerson Clone () {Try { //objects that inherit object//because it's called everything is the type of object, so we're going to have a strong turnPerson frend = (person)Super. Clone (); //create a stored collectionlist<string> list =NewArraylist<string>(); //loop Gets the value manually entered and assigns to the collection of list for(String Person: This. Getfriends ()) {List.add (person); } //frend.setfriends (list); returnfrend; } Catch(clonenotsupportedexception e) {e.printstacktrace (); return NULL; } }}

 PackageChenyang;Importjava.util.ArrayList;Importjava.util.List;/*** Text of the test class * *@author65245 **/ Public classText { Public Static voidMain (string[] args) {//1. Create a direct assignment to the collectionPerson person =NewPerson (); List<String> list =NewArraylist<string>(); List.add ("Hello"); List.add ("Word");        Person.setfriends (list); //2. The method of creating the clone of the person;Person Person1 =Person.clone (); System.out.println ("Person:" +Person ); System.out.println ("Person1:" +person1);}}

Prototype patterns of Java design patterns

Related Article

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.