原型模式

给出一个问题,一个Robot类,有姓名(tom)和身高(150cm),创建10个属性和值一样的类。最简单直接的方法是new 10次这个类。

为了简化操作,可以使用原型模式。

在Spring中 以前获取配置文件时,就用到了原型模式 当然这里的scope是可选的 也可选择singleton 单例模式

原型模式浅拷贝 为了方便,我这里就直接设置属性为Public

//实现克隆方法
public class Robot implements Cloneable{
    public String name;//机器人的名称
    public Srting height;//机器人的身高
    //重写构造方法
    public Robot(String name,String height){
        this.name = name;
        this.height = height;
    }
    //重写克隆方法
    @Override
    protected Object clone()  {
        Robot robot = null;
        try {
            robot = (Robot) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println(e.getMessage());
        }
        return robot;
    }
    
}

现在Robot类的属性都是常用类型,如果添加一个对象类型的话,浅拷贝就无法将对象类型拷贝,还是引用原来的对象,这时就需要深拷贝来完成。

//深拷贝 (推荐使用序列化与反序列化的方式)
public class Robot implements Serializable{
   private static final long serialVersionUID = 1L;
   public String name;
   public String height;
   public Robot friend;//这里给机器人添加一个朋友,同为机器人类
   public Robot(String name,String height,Robot robot){
        this.name = name;
        this.height = height;
        this.robot = robot;
    }

   public RobotdeepCopy(){
     //创建流
    ByteArrayOutputSteam bos = null;
    ObjectOutputSteam oos = null;
    ByteArrayInputSteam bis = null;
    ObjectInputSteam ois = null;
    Robot robot = null;
      try{
        //序列化 
        bos = new ByteArrayOutputSteam();
        oos = new ObjectOutputSteam(bos);
        //将此对象输出
        oos.writeObject(this);
        //反序列化
        bis = new ByteArrayInputSteam(bos.toByteArray());
        ois = new ObjectInputSteam(bis);
        robot  = (Robot)ois.readObject();
      }catch(Exception e){
          Systen.out.print(e.getMessage);
      }finally{
       //关闭流  此处还要try catch,因为没有用编译器,所以这里我就不写了
       ois.close();
       bis.close();
       oos.close();
       bos.close();
     }
     return robot;
   }

}

写完后我们可以来测试一下

public class Test{
   public static void main(String[] a){
       Robot robot1 = new Robot("1号","150cm",new Robot("2号","140cm"));
       Robot robot2 = (Robot)robot1.clone();
       Robot robot3 = robot1.deepCopy();
       //查看他们的hashCode来判断是否是一个对象,主要是看Robot的 friend属性
      System.out.print(robot1.friend.hashCode);
      System.out.print(robot2.friend.hashCode);
      System.out.print(robot3.friend.hashCode);
   }
}

你可能感兴趣的:(原型模式)