简体   繁体   中英

How to prevent changes in a mutable object in immutable object

Can anybody tell how we can prevent a user to modify the values of an mutable object define in an immutable class ?

Example : We have a immutable Student class, which contains final reference of Address class, which is mutable. I want to prevent the user to make any change in Address class?

Arrange for Address to be an interface . Make your mutable MutableAddress as normal and make an ImmutableAddress that wraps it preventing write access to the fields.

interface Address {

    public String getNumber();

    public void setNumber(String number) throws IllegalAccessException;

    public String getStreet();

    public void setStreet(String street) throws IllegalAccessException;

    public String getZip();

    public void setZip(String zip) throws IllegalAccessException;

}

class MutableAddress implements Address {

    String number;
    String street;
    String zip;

    @Override
    public String getNumber() {
        return number;
    }

    @Override
    public void setNumber(String number) {
        this.number = number;
    }

    @Override
    public String getStreet() {
        return street;
    }

    @Override
    public void setStreet(String street) {
        this.street = street;
    }

    @Override
    public String getZip() {
        return zip;
    }

    @Override
    public void setZip(String zip) {
        this.zip = zip;
    }

}

class ImmutableAddress implements Address {

    private final Address address;

    public ImmutableAddress(Address address) {
        this.address = address;
    }

    @Override
    public String getNumber() {
        return address.getNumber();
    }

    @Override
    public void setNumber(String number) throws IllegalAccessException {
        throw new IllegalAccessException("Cannot write to this field.");
    }

    @Override
    public String getStreet() {
        return address.getStreet();
    }

    @Override
    public void setStreet(String street) throws IllegalAccessException {
        throw new IllegalAccessException("Cannot write to this field.");
    }

    @Override
    public String getZip() {
        return address.getZip();
    }

    @Override
    public void setZip(String zip) throws IllegalAccessException {
        throw new IllegalAccessException("Cannot write to this field.");
    }

}

Alternatively, wrap it in a Proxy . This is much more complicated but can help when you do not have access to the sources.

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