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

设计模式-原型模式

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

设计模式-原型模式

问题:

现有一只羊,名为tom,年龄为10岁,颜色为红色,现在需要“克隆出”5只相同的羊

首先使用传统的笨方法实现可以使用如下代码

package com.cxf.test;

public class TestDemo {
    public static void main(String[] args) {
        Sheep sheep=new Sheep("tom",10,"红色");
        Sheep sheep1=new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        Sheep sheep2=new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        Sheep sheep3=new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        Sheep sheep4=new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        Sheep sheep5=new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
        System.out.println(sheep);
        System.out.println(sheep1);
        System.out.println(sheep2);
        System.out.println(sheep3);
        System.out.println(sheep4);
        System.out.println(sheep5);
    }
}
class Sheep{
    private String name;
    private  Integer age;
    private String color;

    public Sheep() {
    }

    public Sheep(String name, Integer age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", color='" + color + ''' +
                '}';
    }
}

传统方式的优缺点

  1. 比较好理解,简单容易操作
  2. 在创建对象时,总是需要重新获取原始对象的属性,如果创建的对象比较复杂时,效率比较低
  3. 总是需要重新初始化对象,而不是动态的获得对象运行时的状态,不够灵活

思路:java中object类是所有类的根类,object类提供了一个clone()方法,该方法可以将一个java对象复制一份,但是需要实现clone的的java类,必须要实现一个接口Cloneable,该接口表示该类能够复制且具有复制的能力=》原型模式

原型模式-基本介绍
  1. 原型模式(prototype)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
  2. 原型模式是一种创建型设计模式,允许一个对象再创建另一个可定制的对象,无需知道如何创建的细节
  3. 工作的原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝他们自己实施创建即 对象.clone()
原型模式再spring框架中源码分析
  1. spring中原型bean的创建,就是原型模式的应用

    beans.xml

    
    
package com.cxf.test;

public class TestDemo {
    public static void main(String[] args) {
        Sheep sheep=new Sheep("tom",10,"红色");
        Sheep sheep1 = sheep.clone();
        Sheep sheep2 = sheep.clone();
        Sheep sheep3 = sheep.clone();
        Sheep sheep4 = sheep.clone();
        Sheep sheep5 = sheep.clone();
        System.out.println(sheep);
        System.out.println(sheep1);
        System.out.println(sheep2);
        System.out.println(sheep3);
        System.out.println(sheep4);
        System.out.println(sheep5);
        System.out.println(sheep==sheep1);//false
        System.out.println(sheep==sheep2);//false
        System.out.println(sheep==sheep3);//false
        System.out.println(sheep==sheep4);//false
        System.out.println(sheep==sheep5);//false
        System.out.println(sheep4==sheep5);//false
    }
}
class Sheep implements  Cloneable{
    private String name;
    private  Integer age;
    private String color;

    public Sheep() {
    }

    public Sheep(String name, Integer age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", color='" + color + ''' +
                '}';
    }

    @Override
    protected Sheep clone() {
        try {
            Sheep sheep=null;
            Sheep clone = (Sheep)super.clone();
            sheep=clone;
            return sheep;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

浅拷贝和深拷贝

浅拷贝的介绍

  1. 对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象
  2. 对于数据类型是引用类型的成员变量,比如说成员变量是某个数组、某个类的对象,那么浅拷贝会进行引用传递,也就是将该成员变量的引用值(内存地址)复制一份给新的对象,因为实际上两个对象的该成员变量都指向同一个实例,在这种情况下,在一个对象中修改成员变量会影响到另一个对象的该成员变量
  3. 默认的clone就是浅拷贝

深拷贝基本介绍:

  1. 复制对象的所有基本数据类型的成员变量值
  2. 为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象进行拷贝
  3. 深拷贝的实现方式1:重写clone方法实现深拷贝 :
  4. 深拷贝的实现方式2:通过对象序列化实现深拷贝

深拷贝举例 这里用的是序列化

package com.cxf.test;

import java.io.*;
import java.util.Arrays;

public class TestDemo2 {
    public static void main(String[] args) {
        try {
            int[] arr={1,2,3};
            Test feifei = new Test("feifei", arr);
            Test clone = feifei.clone();
            System.out.println(feifei.getArr() == clone.getArr());//false
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
class Test implements Serializable,Cloneable {
    private String name;
    private int[] arr;

    public Test(String name, int[] arr) {
        this.name = name;
        this.arr = arr;
    }

    public Test() {
    }

    public String getName() {
        return name;
    }

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

    public int[] getArr() {
        return arr;
    }

    public void setArr(int[] arr) {
        this.arr = arr;
    }

    @Override
    public String toString() {
        return "Test{" +
                "name='" + name + ''' +
                ", arr=" + Arrays.toString(arr) +
                '}';
    }

    @Override
    protected Test clone() throws CloneNotSupportedException {
        ByteArrayOutputStream byteArrayOutputStream=null;
        ObjectOutputStream objectOutputStream=null;
        ByteArrayInputStream byteArrayInputStream=null;
        ObjectInputStream objectInputStream=null;
        try {
            byteArrayOutputStream=new ByteArrayOutputStream();
             objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);
             byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
             objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Test o = (Test)objectInputStream.readObject();
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(objectInputStream!=null)
                    objectInputStream.close();
                if(byteArrayInputStream!=null)
                    byteArrayInputStream.close();
                if(objectOutputStream!=null)
                    objectOutputStream.close();
                if(byteArrayOutputStream!=null)
                    byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/297671.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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