ProtoType Pattern
Hai All,
I tried to use deep cloning procedure for copying exting objects and then set the appropriate values to its properties ( this we do in using prototype pattern ).
But if the properties are simple data types like integer, double etc, their values in the deep cloned object are set to zero. Is there a way to have same value ( for the simple data tyoe properties) of the original object.
The sample code is added below:
/**
* This class extends the class of Javas Point2D.Double
*/
import java.awt.geom.Point2D;
import java.awt.Rectangle;
import java.io.Serializable;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.lang.ClassNotFoundException;
import java.io.IOException;
public class point2D extends Point2D.Double implements Cloneable, Serializable{
// Properties
Color drawColor =Color.red;
/*
* Constructor
*/
point2D(){ }
point2D( double xx, double yy){ super(xx,yy); }
public void setLocation( double xx, double yy){
super.setLocation(xx,yy);}
public void setDrawColor( Color drawColor){
drawColor = this.drawColor;}
/*
* Draw a rectangle around through point.
*/
public Rectangle getPointRect(){
int width = 4;
return new Rectangle( (int)x-width/2,(int)y-width/2, width, width);
}
/*
* Check for a given point coinciding with point2D
* location check is true, if it contains the point
*/
public boolean locationCheck( double x, double y){
return getPointRect().contains((int)x,(int)y);
}
/*
* Draw method.
*/
public void draw( Graphics2D g2d ){
g2d.setColor(drawColor);
g2d.fill( getPointRect());
}
public Object deepClone()
{
try{
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(b);
out.writeObject(this);
out.close();
ByteArrayInputStream bIn = new ByteArrayInputStream(b.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bIn);
oi.close();
return oi.readObject();
}
catch (IOException e)
{ System.out.println("exception:"+e.getMessage());
e.printStackTrace();
return null;
}
catch( ClassNotFoundException cnfe){
System.out.println("exception:"+ cnfe.getMessage());
cnfe.printStackTrace();
return null;}
}
}
public static void main( String[] args){
point2D pp = new point2D();
pp.setLocation( 100.,150.);
System.out.println( pp.locationCheck(100.5, 149.5));
System.out.println( pp.getX() + " " + pp.getY());
point2D ppp = (point2D)pp.deepClone();
System.out.println( ppp.getX() + " " + ppp.getY());
}
}
The output:
true
100.0 150.0
0.0 0.0
Can anyone help me on this issue. Advance thanks to kind help
Chinnaswamy

