不可变对象持久性

时间:2015-01-28 10:29:18

标签: scala functional-programming persistence repository-pattern side-effects

如果我想在持久性之后为对象分配键,您会建议设计软件的方式是什么?我有一个单独的可持久对象类非常不方便,但另一方面我不想使用可变var key。那么选择def Persist_A(toPersist: ImmutablePersistable): Persisteddef Persist_B(toPersist: MutablePersistable): MutablePersistable

的存储库的场景
/**
 * Immutable
 */
class ImmutablePersistable {
    val a: Int = 1
}
class Persisted(
    val obj: ImmutablePersistable,
    val key: String)
/**
 * Mutable
 */
class MutablePersistable {
    val b: Int = 1
    var key: Some[String] = null
}

/**
 * Repository
 * */
class Repo {
    def Persist_A(toPersist: ImmutablePersistable): Persisted = {
        new Persisted(toPersist, "SOME_KEY_HERE")
    }

    def Persist_B(toPersist: MutablePersistable): MutablePersistable = {
        toPersist.key = Some("SOME_KEY_HERE")
        toPersist
    }
}

0 个答案:

没有答案