Item 21: Use function objects to represent strategies

1.  A primary use of function pointers is to implement the Strategy pattern.

 

2.  Some languages support function pointers, delegates, lambda expressions, or similar facilities that allow programs to store and transmit the ability to invoke a particular function.

 

3.  It is possible to define an object whose methods perform operations on other objects, passed explicitly to the methods. An instance of a class that exports exactly one such method is effectively a pointer to that method. Such instances are known as function objects. (i.e. instance of Comparator)

 

4.  A typical concrete strategy class is stateless: it has no fields, hence all instances of the class are functionally equivalent. Thus it should be a singleton to save on unnecessary object creation costs.

 

5.  Because the strategy interface serves as a type for all of its concrete strategy instances, a concrete strategy class needn’t be made public to export a concrete strategy. Instead, a “host class” can export a public static field (or static factory method) whose type is the strategy interface, and the concrete strategy class can be a private nested class of the host. The String class uses this pattern to export a case-independent string comparator via its CASE_INSENSITIVE_ORDER field.

 

你可能感兴趣的:(comparator,function object)