设计模式-原型模式

1.原型模式的简单介绍

原型模式就是指,对于一个类的对象,获得他的一个副本。副本的属性和方法与该对象相同。
在继续了解之前,还有一些预备知识需要明确。

  • 浅复制:对于一个类的对象的简单类型变量,它的副本与其不同。但是对于类类型的变量,副本与原生对象使用的是堆中的同一个。

  • 深复制:一个对象的所有类型的变量,都会额外的拷贝一份。

2.原型模式实现

实际上java已经为我们提供了克隆一个对象的方法,并且定义在了所有类的父类Object中,要想使用该方法,类首先需要实现CloneAble接口。

public class Student implements Cloneable{
    private String name;

    public void setName(String name){
        this.name=name;
    }

    public String getName(){
        return name;
    }

    @Override
    protected Student clone() throws CloneNotSupportedException {
        return (Student)super.clone();
    }
}
public class Client {
    public static void main(String[] args) throws Exception{
        Student student=new Student();
        student.setName("psf");
        Student student1 = student.clone();
        System.out.println(student.hashCode()==student1.hashCode()); 
        //false
    }

上述是典型的浅克隆,Student类中没有自定义的类类型变量。

public class Teacher implements Cloneable{

    private Student student;

    public void show(){
        System.out.println("管理的学生的名字是:"+student.getName());
    }

    public void setStudent(Student student){
        this.student=student;
    }

    public Student getStudent(){
        return student;
    }

    @Override
    protected Teacher clone() throws CloneNotSupportedException {
      return (Teacher) super.clone();
    }
}

对于Teacher类,有一个Student类型的对象,如果我们单纯的返回super.clone(),那么克隆类的student属性都是同一个。

public class Client {
    public static void main(String[] args) throws Exception{
        Teacher teacher=new Teacher();
        Student student=new Student();
        teacher.setStudent(student);

        Teacher teacher1 = teacher.clone();
        System.out.println(student==teacher1.getStudent());
        //true
}

那么如何实现深复制呢。只需要改写clone方法、

 protected Teacher clone() throws CloneNotSupportedException {
      Teacher t=(Teacher) super.clone();
      student=student.clone();
      t.setStudent(student);
      return t;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值