Java原型模式大大节省资源测试

但你需要创建大量相同对象的时候,使用原型模式吧!原型模式

 

 


 

 

克隆猫猫:

public class CloneCat implements Cloneable {
    public CloneCat() {
        try {
            Thread.sleep(10);//模拟创建类耗时耗力
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

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

测试代码:

class Test {
    //使用new创建100个猫猫对象
    static void test1(){
        Date start = new Date();
        for(int i =0;i<100;i++){
            CloneCat temp = new CloneCat();
        }
        Date end = new Date();
        System.out.println("new  耗时:"+(end.getTime()-start.getTime()));
    }

    static void test2() throws CloneNotSupportedException {
        Date start = new Date();
        //使用克隆创建100个猫猫对象
        CloneCat cloneCat = new CloneCat();
        for(int i =0;i<100;i++){
            CloneCat temp = (CloneCat) cloneCat.clone();
        }

        Date end = new Date();
        System.out.println("clone  耗时:"+(end.getTime()-start.getTime()));
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        test1();
        test2();
    }
}

测试结果:

 

posted @ 2022-11-23 19:41  在博客做笔记的路人甲  阅读(19)  评论(0编辑  收藏  举报