日历的防御副本 [英] Defensive copy of Calendar

查看:135
本文介绍了日历的防御副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图寻找实现日历对象的防御副本的方法的最佳方法。

Been trying to find the best way to implement a method that makes a defensive copy of a Calendar object.

例如:

public void setDate(Calendar date) {
    // What to do.... 
}

我特别关心在检查null输入和复制时交错线程,或者我缺少一些很明显的东西?

I am particularly concerned about interleaving of threads when checking for null input and making the copy or am I missing something very apparent?

推荐答案

(目标对象略有不同,我猜...)

(Aimed at a slightly different audience now, I guess...)

如果我完全不得不使用 Calendar (而不是Joda Time),我将使用 clone()。你在评论中认为你担心淘气的子类 - 你会如何建议在任何计划中解决这个问题?如果你不了解所涉及的子类,并且不相信它们,那么你没有办法保存类型特定的数据。如果你不相信子类不要乱七八糟,你一般有更大的问题。

I would use clone() if I absolutely had to use Calendar at all (instead of Joda Time). You argue in comments that you're worried about a "naughty subclass" - how would you propose to work around that in any scheme? If you don't know anything about the subclasses involved, and don't trust them, then you've got no way of preserving type-specific data. If you don't trust the subclass not to mess things up, you've got bigger problems in general. How do you trust it to give you the right results when performing date/time calculations?

clone()是在执行日期/时间计算时,克隆对象的 expected 方式:它是我期望一个敏感的子类挂钩在任何需要的类型特定的行为。你不需要知道哪些位的状态是相关的 - 你只是让类型处理本身。

clone() is the expected way of cloning objects: it's where I'd expect a sensible subclass to hook in any type-specific behaviour it needed. You don't need to know which bits of state are relevant - you just let the type deal with that itself.

使用日历的好处。 getInstance()并自行设置属性:


  • 您将保留相同的日历类型

  • 你不需要担心忘记属性:这是类型的责任

  • 你明确地说: 做,并让实现照顾如何,这总是很好。

  • You'll preserve the same calendar type
  • You don't need to worry about forgetting properties: that's the responsibility of the type
  • You're explicitly saying what you want to do, and letting the implementation take care of the how, which is always nice. Your code expresses your intention exactly.

编辑:就原始问题担心的线程交叉而言: date 参数不会改变。但是,如果另一个线程正在改变对象的内容,而你采取防御性副本,那可以很容易导致问题。如果这是一个风险,那么你会有更大的问题,基本上。

In terms of the "thread interleaving" which the original question worries about: the value of the date parameter will not change whatever other threads do. However, if another thread is mutating the contents of the object while you take a defensive copy, that could very easily cause problems. If that's a risk, then you've got bigger issues, basically.

这篇关于日历的防御副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆