Java设计模式之原型模式

Java23种设计模式

原型模式就是克隆自身,是用于解决对象重复创建消耗性能的问题,或者数据的备份。

需求:我们要克隆一个细胞(母细胞)100次(取名细胞1-100),已知创造这个细胞耗时一秒钟。

1. 传统方式应该是每次new一个对象:

先创建细胞类Cell

public class Cell {
    private String name;
    private String age;

    public Cell(String name, String age) {
        try {
            Thread.sleep(1000);
            this.name = name;
            this.age = age;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

然后创建Test类执行操作:

public class Test {
    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println("开始"+df.format(new Date()));// new Date()为获取当前系统时间
        Cell cell = new Cell("母细胞","100岁");
        List<Cell> cellList = new ArrayList<>();
        cellList.add(cell);
        for(int i = 0;i<100;i++){
            cellList.add(new Cell("细胞"+(i+1),"100岁"));
        }
        System.out.println("结束"+df.format(new Date()));
    }

}

耗时:1分41秒

开始2019-05-05 18:13:22
结束2019-05-05 18:15:03

2. 原型模式克隆对象:

实现Cloneable接口

public class Cell implements Cloneable{
    private String name;
    private String age;

    public Cell(String name, String age) {
        try {
            Thread.sleep(1000);
            this.name = name;
            this.age = age;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

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

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

修改代码逻辑

public class Test {
    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println("开始"+df.format(new Date()));// new Date()为获取当前系统时间
        Cell cell = new Cell("母细胞","100岁");
        List<Cell> cellList = new ArrayList<>();
        cellList.add(cell);
        for(int i = 0;i<100;i++){
            try {
                Cell c = (Cell) cell.clone();
                c.setName("细胞"+(i+1));
                cellList.add(c);
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("结束"+df.format(new Date()));
    }
}

耗时:1秒

开始2019-05-05 18:23:05
结束2019-05-05 18:23:06

原理是克隆没有走构造方法,而是直接底层复制当前对象,所以原型模式适合生成重复对象或对象的备份问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值