publicclassClient {publicstaticvoidmain(String[] args) {WordDocument originDoc =newWordDocument();originDoc.setText("This is a document");originDoc.addImage("Image 1");originDoc.addImage("Image 2");originDoc.addImage("Image 3");originDoc.showDocument();WordDocument copyDoc =originDoc.clone();copyDoc.showDocument();copyDoc.setText("This is a copy document");copyDoc.showDocument();originDoc.showDocument(); }}
-------------init-------------
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------
-------------Start-------------
Text : This is a copy document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------
根据输出结果,可以发现,当我们克隆产生的对象修改时,其原型不会改变
但,真的是这样吗?
我们再来测试一下,我们给 copyDocument 添加图片信息
仍然是Client类的main函数中
...WordDocument copyDoc =originDoc.clone();copyDoc.showDocument();copyDoc.setText("This is a copy document");// add this line to test the origin document what will happen when the copy document add a imagecopyDoc.addImage("a new Image");copyDoc.showDocument();originDoc.showDocument();
输出结果:
...
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------
-------------Start-------------
Text : This is a copy document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
Image Name : a new Image
------------- End -------------
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
Image Name : a new Image
------------- End -------------
-------------init-------------
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------
-------------Start-------------
Text : This is a copy document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
Image Name : a new Image
------------- End -------------
-------------Start-------------
Text : This is a document
Image List :
Image Name : Image 1
Image Name : Image 2
Image Name : Image 3
------------- End -------------