什么是包装器类? 这样的类有什么用处呢?
当前回答
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.
其他回答
有几种设计模式可以称为包装器类。
请参阅我对“代理、装饰器、适配器和桥接模式有何不同?”
让一个包装类变得健康并不是一件容易的事情。 了解包装器类是如何被其他人设计的也不是一件容易的事情。 因为这是想法,不是代码。 只有理解了理念,才能理解包装。
包装器类提供了一种将基本类型用作对象的方法。对于每个原语,我们都有一个包装器类,比如,
int Integer
byte Byte
Integer和Byte是原语int和Byte的包装类。当您需要将原语作为对象使用时,有时会有限制,因此包装类提供了一种称为装箱/拆箱的机制。
下面的例子可以很好地理解这个概念
double d = 135.0 d;
Double doubleWrapper = new Double(d);
int integerValue = doubleWrapper.intValue();
byte byteValue = doubleWrapper.byteValue();
string stringValue = doubleWrapper.stringValue();
这就是方法,我们可以使用包装器类类型转换成其他基本类型。当您需要将原语类型转换为对象并使用它们来获取其他原语时,就会使用这种类型的转换。但是对于这种方法,您需要编写一个大代码。但是,使用简单的强制转换技术也可以实现同样的效果,代码片段如下所示
double d = 135.0;
int integerValue = (int) d ;
虽然double值显式转换为整数值,也称为向下转换。
我目前在我的项目中使用了一个包装器类,我得到的主要好处(只是一个扩大主题解释的好处):
异常处理:我的主类(另一个类包装的类)具有在发生异常时抛出异常的方法,因此我创建了一个包装类来处理异常并立即记录它们。因此,在我的主作用域中,没有异常处理。我只是调用一个方法并做一些事情。
易于使用:我可以很容易地启动对象。通常起始阶段由很多步骤组成。
代码可读性:当另一个程序员打开我的代码时,代码看起来非常清晰,易于操作。
隐藏细节:如果你正在生成另一个程序员将要使用的类,那么你可以包装细节,如“错误处理,异常处理,日志消息等……”,这样程序员就不必处理混乱,只需要简单地使用方法。
包装器是用于在不同平台之间的两个不同应用程序之间进行通信的类