Cloneable Interface Design

A cloneable interface design often requires a clear separation between a type and its implementation. Often it is unavoidable to provide a public clone() operation for such a type when the type is used as part of the state of an object.  A cloneable interface design relies on the following factors:

Cloneable Interface Design Forces and Facts

  1. Accessor methods in Java should return a copy of internal state variables instead of references to the internal variables – in order to maintain an object’s integrity
  2. When values given to constructors are to become part of the state of an Object and should be copied instead of just referenced.
  3. There are no constructors available in an interface declaration, so a “copy constructor” cannot be declared.
  4. The visibility of a clone() method needs to be public to allow arbitrary client classes to clone the object

Example of Problem:

public interface State {
//
// some operations
//
}

public class C { public C (State s) { 
state = new State(s); 
state = s; 
}

public State getState() { 
return state; 
}

protected State state; 
}

Solution:

public interface State extends java.lang.Cloneable {
        //
        // some operations
        //
public Object clone();
}

public class C { public C(State s) { 
state = (State)s.clone(); 
}

public State getState() { 
return (State)state.clone(); 
}

protected State state; 
}

Booker Showers