简体   繁体   English

在java中将可变变量转换为不可变,痛苦更少

[英]convert mutable variable to immutable in java with less pain

sometime i have no choice to use mutable variable instead of immutable variables i know how many ways can create immutable vars but i wonder this way also correct its really convert mutable to immutable and i dont use concurrency or multithreading in my code just Curious? 有时我没有选择使用mutable变量而不是immutable变量我知道有多少种方法可以创建不可变变量但是我想知道这种方式也正确它真正转换为mutable变为immutable并且我不在我的代码中使用concurrency或多multithreading只是好奇吗?

public class Config implements FindIt {
....
    private final class DateHolder{

    private final Date dateContainDateObject;

    DateHolder(String date) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        dateContainDateObject = dateFormat.parse(date);
    }

    public Date getDate(){
        return dateContainDateObject;
    }

   }
}

this is nested class and i use it like 这是嵌套类,我喜欢它

private DateHolder holder;

and fill the holder variable in Config constructor class so holder variable are ThreadSafe ? 并在Config构造函数类中填充holder变量,所以holder变量是ThreadSafe

Date is a mutable object. 日期是一个可变对象。 Making it final means you can't change the reference to it, but you can still change what's at the reference (java.util.Date/Calendar nastiness strikes again, switch to the Java 8/Joda Time way if you can). 使它成为最终意味着你不能改变对它的引用,但你仍然可以改变引用的内容(java.util.Date/Calendar nastiness再次出现,如果可以的话,切换到Java 8 / Joda Time方式)。

Don't expose any references to the Date member to the outside world. 不要将对Date成员的任何引用暴露给外部世界。 Instead make a defensive copy and pass that back instead. 而是制作防御性副本并将其传回。 You might consider saving the time value as a final long instance member and only instantiating a Date when you need it. 您可以考虑将时间值保存为最终的长实例成员,并仅在需要时实例化Date。

can say is safe when you make class private and non-static, when you create form Config class you have only one DateHolder . 当你创建私有和非静态类时,可以说是安全的,当你创建表单Config类时,你只有一个DateHolder。

http://www.javapractices.com/topic/TopicAction.do?Id=29 http://www.javapractices.com/topic/TopicAction.do?Id=29

why is static inner class singleton thread safe 为什么静态内部类单例线程安全

http://www.javatpoint.com/how-to-create-immutable-class http://www.javatpoint.com/how-to-create-immutable-class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM