什么是包装器类? 这样的类有什么用处呢?


当前回答

包装器类是一个包装另一个类并提供客户端和被包装的原始类之间的抽象的类。

其他回答

包装类是一个“包装”其他东西的类,就像它的名字一样。

它更正式的定义是实现适配器模式的类。这允许您将一组api修改为更可用、更可读的形式。例如,在c#中,如果你想使用本机Windows API,它有助于将它包装成一个符合. net设计准则的类。

包装器类是围绕基本数据类型的包装器。它表示基元数据类型在其对应的类实例中,例如布尔数据类型可以表示为布尔类实例。Java中所有的基本包装类都是不可变的,即一旦给包装类实例赋值,就不能再修改。

包装器类是唯一用于保存某些东西并向其添加一些功能的类。 在Java中,由于原语(如int,float,char…)不是对象,所以如果你想把它们当作一个对象,那么你必须使用包装类。 假设你想创建一个int型的Vector,问题是Vector只保存对象而不是原语。所以你要做的就是把所有的整型放在一个Integer包装器中并使用它。例子:

int number = 5;
Integer numberWrapped = new Integer(number);
//now you have the int in an object.
//and this is how to access the int value that is being wrapped.
int again = numberWrapped.intValue();

有几种设计模式可以称为包装器类。

请参阅我对“代理、装饰器、适配器和桥接模式有何不同?”

In general, a wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. These are useful by providing a level of abstraction from the implementation of the underlying class or component; for example, wrapper classes that wrap COM components can manage the process of invoking the COM component without bothering the calling code with it. They can also simplify the use of the underlying object by reducing the number interface points involved; frequently, this makes for more secure use of underlying components.