Avoid implementing clone.
-
clone is very tricky to implement correctly in all circumstances, nearly to the point of being pathological
- the importance of copying objects will always remain, since object fields often need to be defensively copied
-
copy constructors and static factory methods provide an alternative to clone, and are much easier to implement
If you need to extend a superclass that implements clone, then your subclass must implement clone as well. The quickest solution is for your subclass to simply throw an exception.
Example
This example shows a superclass with a typical implementation of clone, and a subclass which has disabled its clone method.
import java.util.Date;
public abstract class Fruit implements Cloneable {
public Fruit( String aColour, Date aBestBeforeDate ) {
super();
fColour = aColour;
//defensive copy needed for this mutable object
fBestBeforeDate = new Date( aBestBeforeDate.getTime() );
}
public abstract void ripen();
public String getColour() {
return fColour;
}
public Date getBestBeforeDate() {
//return defensive copy of this mutable object
return new Date ( fBestBeforeDate.getTime() );
}
/**
* Implement clone as follows
* <ul>
* <li>the class declaration "implements Cloneable" (not needed if already
* declared in superclass)
* <li>declare clone method as public
* <li>if the class is final, clone does not need to throw CloneNotSupportedException
* <li>call super.clone and cast to this class
* <li>as in defensive copying, ensure each mutable field has an independent copy
* constructed, to avoid sharing internal state between objects
* </ul>
*/
@Override public Object clone() throws CloneNotSupportedException {
//get initial bit-by-bit copy, which handles all immutable fields
Fruit result = (Fruit)super.clone();
//mutable fields need to be made independent of this object, for reasons
//similar to those for defensive copies - to prevent unwanted access to
//this object's internal state
result.fBestBeforeDate = new Date( this.fBestBeforeDate.getTime() );
return result;
}
/// PRIVATE ////
/**
* Strings are always immutable.
*/
private String fColour;
/**
* Date is a mutable object. In this class, this object field is to be treated
* as belonging entirely to this class, and no user of this class is
* to be able to directly access and change this field's state.
*/
private Date fBestBeforeDate;
}
Here is the subclass, with its clone method disabled.
import java.util.Date;
public final class Apple extends Fruit {
public Apple( String aColour, Date aBestBeforeDate ) {
super( aColour, aBestBeforeDate );
}
public void ripen() {
//empty implementation of abstract method
}
/**
* The Apple subclass does not support clone.
*/
@Override public final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
This article originates from http://www.javapractices.com/topic/TopicAction.do;jsessionid=F5C214E7452424EA265D4DD5A493BF2B?Id=71
分享到:
相关推荐
For the security of your Github account, please always avoid revealing the AccessToken to third parties, including , veaba ](), veaba-bot will not keep storing your AccessToken info
Netlify's deployment infrastructure(基础设施) knows how to avoid uploading the same file twice, even between different deploys, so we get your changes ready without duplicating content.
# Avoid using sudo with npm; take ownership! sudo chown -R $USER /usr/local # Install the npm in linc-sony-demo cd linc-sony-demo ; npm install # Run the app using the default command gul
Build, Windows, Mac OS and Linux are supported, build bygit clone git@github.com:downdemo/Design-Patterns-in-Cpp17.gitcd Design-Patterns-in-Cpp17cmake . -Bbuildcd buildcmake --build .设计模式简介设计...
5. **条目5:重用对象以减少装箱开销(Avoid Creating Unnecessary Objects)** 对于装箱基本类型,重复创建对象会增加内存消耗和性能开销。尽可能重用对象,或者使用原始类型代替。 6. **条目6:消除过期的对象...
克隆此存储库: git clone tw.org/html/tools更新说明首次使用时,请生成API令牌并将其安全存储以备后用: :不需要特殊的范围然后设置Python 3环境: # Create a virtual environment to avoid clobbering global ...
in your `requirements.txt` to avoid trying to install newest source package. ### Install from source 1. Download source by `git clone` or [zipfile]...
前端应用程序管理门户 概述 frontend-app-admin-portal是提供...$ nvm use (if using nvm) OR install and switch to version of node/npm as per the .nvmrc file to avoid issues during npm install or npm start
pip3 install pivotnacci从存储库: git clone https://github.com/blackarrowsec/pivotnacci.gitcd pivotnacci/pip3 install -r requirements.txt # to avoid installing on the OSpython3 se
:elephant: o CLI工具,可帮助您进行PostgreSQL数据库架构更新,... # All variables are mandatory to avoid mixed environments. # Connection strings: https://www.postgresql.org/docs/current/libpq-connect.h
page-break-inside: avoid; font-family: sans-serif; /* 或其他适合打印的字体 */ } /* 其他针对打印的CSS规则 */ } ``` 5. **调用浏览器打印功能**:使用`window.print()`方法触发打印对话框,让用户可以...
# Avoid checking CSRF auth.token.check.enabled=false 安装 需要NodeJS 10+ git clone https://github.com/p2kmgcl/page-editor-dev-server cd page-editor-dev-server npm install npm link 跑步 cd ~/my/local/...
Purpl引擎3.0 这是我制作游戏引擎的第三次尝试。 从这些尝试中学到的东西,我认为这将是件好事。 我的目标是在某个时候拥有创建游戏所必需的...# To avoid CMake complaining about glew not getting any sources, is
* [MNG-4918] - MavenProject#clone() doubles active profiles * [MNG-4919] - Plugin execution contributed by lifecycle mapping gets lost when same goal is bound multiple times * [MNG-4923] - ...
* "git clone --recurse-submodules" learned to set up the submodules to ignore commit object names recorded in the superproject gitlink and instead use the commits that happen to be at the tip of ...
- **Approach:** Reuse objects when possible and avoid creating temporary objects. **Item 17: Implement the Standard Dispose Pattern** - **Pattern:** Ensures proper disposal of unmanaged resources. -...
This should be done carefully to avoid losing important changes. - **Disaster Recovery**: If something goes wrong, Git provides several recovery mechanisms. For example, you can recover deleted ...
如何使用要使用它,您只需要在/etc/nixos克隆该存储库: git clone git@github.com:squiter/nix-config.git /etc/nixoschown -R 1000:100 /etc/nixos # to avoid need root to edit the files然后,您可以按照系统的...
$overlay.append($img.clone().addClass('enlarged')); $('body').append($overlay); $overlay.fadeIn(); // 显示大图层 // 计算并设置大图的位置和大小 var imgPos = $img.position(); var imgWidth = $img....
Instead of creating a new character from scratch every time, you could clone an existing character as a prototype, then modify the cloned character with different attributes like strength, speed, or ...