简体   繁体   中英

Return immutable copy of mutable object from method

I have some closed component which is working over some XML object. I need to expose this object outside of this component, but I don't want to allow changes on it outside of my component. How can I complete this?

Ensure your object has a copy constructor that allows you to make a deeply-cloned copy of your class.

Then call this when you return the object, eg

SomeClass instance = // ....


public SomeClass getInstance() {
  return new SomeClass(instance);
}

This won't make the returned object immutable. But it doesn't need to be - you just don't want the external code making changes to your copy of the data.

Well, here is the access level's advocate ;-)

If you just wish to prevent the caller from making changes, it doesn't mean that it has to be immutable [in your package] - it just means that it shouldn't have a [public] way to mutate it :) I'm actually a growing fan of returning a limiting public interface .

For instance:

// Option A with a "limiting public interface"
public interface Awesome {
    public String getText();
}

class MyAwesome implements Awesome {
    public String getText() {
       // ..
    }
    // Option B is to make setText non-public
    public void setText() {
       // ..
    }
}

Then your code can return Awesome which doesn't [directly] provide a way mutate the object.

I think you need to create another class which is immutable, taking your object as a parameter (maybe in constructor). Then you should only expose the instance of your new class.

Here's some tips to make an object immutable: Immutable class?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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