如何使可变对象变为不可变的? (不是在创建时) [英] How to make a mutable object to immutable? (not at creation)

查看:95
本文介绍了如何使可变对象变为不可变的? (不是在创建时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,首先需要创建一个(可变的)对象,在某些情况下,我需要使其成为不可变的(我不想在创建时使其成为不可变的).有什么好的方法可以实现吗? 要求是在一段时间内将其从可变状态更改为不可变,使用final将不起作用.

I have a use case where I need to create a (mutable)object first, and at certain scenario I need to make it immutable(I don't wanna make it immutable upon creation). Is there a good way to achieve it? The requirement is to change it from mutable to immutable at some time, using final will not work.

推荐答案

一个对象不能同时可变和不可变.您可以做的是,您可以在可变对象中有一个方法来返回相应的不可变对象.

An object cannot be mutable and immutable at the same time. What you can do is you can have a method in your mutable object to return corresponding immutable object.

这是我所说的实现的一个例子.

Here is an example of implementation of what I am saying.

class BasicMutable {
    private int i;

    public void setI(int i){
        this.i = i;
    }

    public void getI(){
        return i;
    }

    public BasicImmutable getImmutable(){
        return new BasicImmutable(this);
    }
}

现在创建不可变对象

class BasicImmutable {
    private final i;

    BasicImmutable(BasicMutable bm){
        this.i = bm.i;
    }

    public void getI(){
        return i;
    }
}

您还可以在BasicImmutable中使用getMutable()方法来获取相应的Mutable对象.

You can also have a getMutable() method in BasicImmutable to get corresponding Mutable object.

这篇关于如何使可变对象变为不可变的? (不是在创建时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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