public interface Copyable
Copyable
are capable of
copying their internal, persistent state to another object that
can be cast to the same type. This interface therefore provides
a standard means by which data objects can be copied.The main usefulness in copying has to do with the UI. When bringing up a modal dialog or any other form of cancellable UI, it is a good practice to have the dialog operate on a copy of the data rather than the original. As the user moves from one panel to another within the dialog, there may be complex interdependencies among panels on different data objects. To prevent panels from having to access the data cached in each other's UI components, the edited data is flushed to the data object copy when the user moves to a different panel. Then the interdependencies are between the panels and the data objects instead of between the panels themselves. This preserves the separation of "model" and "view" in model-view-controller terms.
Modifier and Type | Method and Description |
---|---|
java.lang.Object |
copyTo(java.lang.Object target)
Copies the internal state of
this object to the
specified copy . |
java.lang.Object copyTo(java.lang.Object target)
this
object to the
specified copy
. If copy
is
null
, then this method should create a new instance
of this
class and proceed to copy the internal state
to the newly created object. Generally, only the persistent
state of the object should be copied, but whether or not it is
appropriate to copy transient properties is at the discretion
of the individual implementor.
Regardless of whether the copy occurs to an existing object or to
a newly created object, the return value is object to which
this
object's state was copied.
There is a standard implementation pattern for the
copyTo
method that helps avoid problems that arise
when a Copyable
object is subclassed. The pattern
is:
The parameter passed into thepublic Object copyTo( Object target ) { final <this_class> copy = target != null ? (<this_class>) target : new <this_class>(); copyToImpl( copy ); return copy; } protected final void copyToImpl( <this_class> copy ) { super.copyToImpl( copy ); // if necessary // put code here for copying the properties of <this_class> }
copyToImpl
method is
the same type of this
class. The responsibility of
copyToImpl
is to copy the state of this
class through direct access of the fields. The
copyToImpl
method should not use getters and setters
since these may be overridden, causing the state of
this
class to be incompletely copied.target
- The target object to which the state of
this
object should be copied. If target
is null
, then the copyTo
method will
return a new instance of this
class.this
object was copied. If the target
was
non-null
, then the return value is the same as the
target
object that was passed in; otherwise, the
return value is a new instance of this
class.java.lang.ClassCastException
- if target
is
non-null
and cannot be downcast to the type of
this
object.