什么是包装器类? 这样的类有什么用处呢?
当前回答
值得注意的是,在某些环境中,包装器类所做的大部分工作都被方面所取代。
编辑:
一般来说,包装器将对包装所做的事情进行扩展,而不关心包装的实现,否则,包装与扩展被包装的类没有任何意义。一个典型的例子是围绕一些其他服务接口添加计时信息或日志功能,而不是将其添加到该接口的每个实现中。
This then ends up being a typical example for Aspect programming. Rather than going through an interface function by function and adding boilerplate logging, in aspect programming you define a pointcut, which is a kind of regular expression for methods, and then declare methods that you want to have executed before, after or around all methods matching the pointcut. Its probably fair to say that aspect programming is a kind of use of the Decorator pattern, which wrapper classes can also be used for, but that both technologies have other uses.
其他回答
包装器类通常是一个具有对象作为私有属性的类。包装器实现了私有对象的API,所以它可以作为私有对象的参数传递。
假设您有一个集合,并且希望在向其中添加对象时使用某种转换—您编写一个具有集合的所有方法的包装器类。当调用add()时,包装器转换参数,而不是仅仅将它们传递到私有集合中。
包装器可以在任何可以使用集合的地方使用,私有对象仍然可以有其他对象引用它并读取它。
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.
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();
包装类是一个“包装”其他东西的类,就像它的名字一样。
它更正式的定义是实现适配器模式的类。这允许您将一组api修改为更可用、更可读的形式。例如,在c#中,如果你想使用本机Windows API,它有助于将它包装成一个符合. net设计准则的类。