Object Wrap

I have an Object that comes and has a bunch of public attributes, not getters and setters. BADLY! So I created a class with attributes and created getters and setters for them. My plan is to wrap an object in my class so that it does not indicate direct access to attributes. I do not know how to do this. I understand that a great casting. How exactly can I wrap a class in my safe class using getters and setters and access attributes through my recipients and setters?

+3
source share
3 answers

Maybe so?

class MyCar implements ICar{

    private final Car car;
    public MyCar(Car car)
    {
         this.car = car;
    }

    public string getModel()
    {
          return car.model;
    }

    public void setModel(string value)
    {
          car.model = value;
    }

}

, Car, MyCar, , ICar, , ( , ).

+6

. Exposed,

public class ExposedProtector {
    private Exposed exposed;  // private means it can't be accessed directly from its container

    //public/protected methods here to proxy the access to the exposed.



}

: Exposed. , , .

java. , .

+3

If you want your class to be compatible with the plugin with the source class (this means that the client code does not need to change the types of variables), your class must be a subclass of the class that expects the client code. In this case, you cannot hide public variables, although you can easily add getters and setters. However, even if you use a subclass, this will not help if the source class has other subclasses; they will not see those getters and setters.

If you can introduce an unrelated class, then the solution should delegate everything:

public class BetterThing {
    private Thing thing;
    public BetterThing(Thing thing) {
        this.thing = thing;
    }
    public int getIntProperty1() {
        return thing.property1;
    }
    public void setIntProperty1(int value) {
        thing.property1 = value;
    }
    // etc.
}
+2
source

All Articles