包装对象

问题描述

| 我有一个对象,它有很多公共属性,没有getter和setter方法。坏! 因此,我创建了一个带有属性的类,并为其创建了吸气剂和吸气剂。我的计划是将对象包装在类中,这样就意味着不直接访问属性。 我不确定如何执行此操作。我知道精打细算。 我该如何精确地将类与安全类(包含getter和setter)包装在一起,并通过我的getter和setter获得对属性的访问权限?     

解决方法

也许是这样吗?
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;
    }

}
现在,您可以绕过具有getter和setter的
MyCar
实例,也可以绕过
ICar
的引用,而这将使您完全控制要公开的内容(例如,可以公开getter),而不是传递
Car
的实例。     ,使用组成。如果您将具有公共属性的类称为“公开的”,则只需
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访问修饰符。从私有到受保护再到公共,访问级别各不相同。     ,如果您希望您的类与原始类具有插件兼容性(这意味着客户端代码不需要更改变量类型),则您的类将必须是客户端代码期望的类的子类。在这种情况下,尽管可以轻松添加getter和setter,但是您无法隐藏公共变量。但是,即使您是子类,但是如果原始类具有其他子类也无济于事。他们看不到那些吸气剂和吸气剂。 如果可以引入一个不相关的类,那么解决方案是委派所有内容:
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.
}