原型模式(java实现)

原型模式

介绍

原型模式用于创建重复的对象,同时又能保证性能。

java实现

实现原型模式需要两步:

  1. 实现Cloneable接口
  2. 重写clone方法

例如我们定义一个Video

import lombok.*;
import java.time.*;

@Data
@AllArgsConstructor
public class Video implements Cloneable{
    private String name;
    private LocalDateTime createTime;

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

创建main函数,测试clone方法:

import java.time.*;

public class App {
    public static void main(String[] args) throws CloneNotSupportedException {
        LocalDateTime localDateTime = LocalDateTime.of(2020, 2, 8, 19, 32);
        Video v1 = new Video("设计模式.mp4", localDateTime);
        Video v2 = (Video) v1.clone();
        System.out.println(v1);
        System.out.println(v2);
        System.out.println(v1 == v2);
    }
}

运行结果:

Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
false

可以看出v1和v2是两个不同的对象,但是内容完全相同

深克隆

刚才的代码虽然实现了克隆,但是v1和v2中的createTime属性都是LocalDateTime类的对象的引用:

import java.time.*;

public class App {
    public static void main(String[] args) throws CloneNotSupportedException {
        LocalDateTime localDateTime = LocalDateTime.of(2020, 2, 8, 19, 32);
        Video v1 = new Video("设计模式.mp4", localDateTime);
        Video v2 = (Video) v1.clone();
        System.out.println(v1.getCreateTime() == v2.getCreateTime());
    }
}

运行结果:

true

要解决这个问题只需要改造一下clone方法,在clone对象的时候,将createTime属性同时克隆一份

import cn.hutool.core.util.*;
import lombok.*;

import java.time.*;

@Data
@AllArgsConstructor
public class Video implements Cloneable {
    private String name;
    private LocalDateTime createTime;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Video v = (Video) super.clone();
        v.setCreateTime(ObjectUtil.clone(createTime));
        return v;
    }
}

再次运行测试:

import java.time.*;

public class App {
    public static void main(String[] args) throws CloneNotSupportedException {
        LocalDateTime localDateTime = LocalDateTime.of(2020, 2, 8, 19, 32);
        Video v1 = new Video("设计模式.mp4", localDateTime);
        Video v2 = (Video) v1.clone();
        System.out.println(v1);
        System.out.println(v2);
        System.out.println(v1.getCreateTime() == v2.getCreateTime());
    }
}

运行结果:

Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值