栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式-原型模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式-原型模式

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;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/315219.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号