简体   繁体   English

从方法返回可变对象的不可变副本

[英]Return immutable copy of mutable object from method

I have some closed component which is working over some XML object.我有一些封闭的组件正在处理一些 XML 对象。 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 .如果您只是希望阻止调用者进行更改,这并不意味着它必须是不可变的 [在您的包中] - 它只是意味着它不应该有 [public] 方式来改变它:) 我'我实际上越来越喜欢返回一个有限的公共接口

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.然后你的代码可以返回Awesome ,它不会[直接]提供改变对象的方法。

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?以下是使对象不可变的一些技巧:不可变的类?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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