包装一个对象 [英] wrapping an Object

查看:59
本文介绍了包装一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它有一堆公共属性,没有 getter 和 setter.坏的!所以我创建了一个具有属性的类,并为它们创建了 getter 和 setter.我的计划是将对象包装在我的类中,因此这意味着不能直接访问属性.我有点不确定如何做到这一点.我理解铸造很好.我究竟如何用我的安全类和 getter 和 setter 包装类,并通过我的 getter 和 setter 访问属性?

I have an Object which comes and has a bunch of public attributes and no getters and setters. BAD! So I created a class with the attributes and created getters and setters for them. My plan is to wrap the object in my class so it means no direct access to attributes. I'm kind of unsure how to do this. I understand casting fine. How exactly could I wrap the class with my safe class with getters and setters and gain access to the attributes via my getters and setters?

推荐答案

也许是这样?

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 的实例,您可以传递具有 getter 和 setter 的 MyCar 实例或对 ICar 的引用> 这将使您能够准确地控制要公开的内容(例如,您可以只公开 getter).

now instead of passing around an instance of Car, you can either pass around MyCar instance which has getters and setters or a reference to ICar which will let you control exactly what you would like to expose (for example you could just expose the getters).

这篇关于包装一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆