我最初想创建一个可以在构造函数中中止实例化的类,但根据此链接,我应该改用 Factory 类。但是现在我想阻止除工厂类之外的任何人创建“Inner”类的对象,同时向所有人提供对内部类方法的访问权限。
我已经尝试过这个答案。
import java.util.Date
object InnerFactory {
class Inner private constructor(startDate: Date? = null, endDate: Date? = null) {
fun getTimeDifference(): Long? {
//calculates time difference but doesn't matter to this example
}
}
fun createInnerObject(startDate: Date? = null, endDate: Date? = null): Inner? {
if (startDate != null && endDate != null && !endDate.after(startDate)) {
return null
}
return Inner(startDate, endDate)
}
}
Run Code Online (Sandbox Code Playgroud)
我会像下面这样使用它:
val date1 = Date(1547600000)
val date2 = Date(1547600600)
val inner = InnerFactory.createInnerObject(date1, date2) //should return an instance
val invalidInner = InnerFactory.createInnerObject(date2, date1) //should not return an instance because the "endDate" is before "startDate"
val difference = inner?.getTimeDifference()
Run Code Online (Sandbox Code Playgroud)
将鼠标悬停在“createInnerObject”函数中我对构造函数的使用上时,它说“无法访问 '<init>':它在 'Inner' 中是私有的”。
你可以做什么:
interface Inner应该公开的所有必要功能private并实现该接口样本:
object InnerFactory {
interface Inner {
fun getTimeDifference(): Long?
}
private class InnerImpl(startDate: Date? = null, endDate: Date? = null) : Inner {
override fun getTimeDifference(): Long? = TODO("some implementation")
}
fun createInnerObject(startDate: Date? = null, endDate: Date? = null): Inner? {
if (startDate != null && endDate != null && !endDate.after(startDate)) {
return null
}
return InnerImpl(startDate, endDate) // InnerImpl accessible from here but not from outside of InnerFactory...
}
}
Run Code Online (Sandbox Code Playgroud)
现在您无法再InnerImpl从外部访问,但仍然可以使用所有必要的功能:
// the following all work as it deals with the interface
val inner = InnerFactory.createInnerObject(date1, date2) //should return an instance
val invalidInner = InnerFactory.createInnerObject(date2, date1) //should not return an instance because the "endDate" is before "startDate"
val difference = inner?.getTimeDifference()
// the following will not compile:
InnerImpl()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1320 次 |
| 最近记录: |