Theory

In the Java the function pointers is implemented by the declaring an interface to represent strategy and a class that implements this interface for each concrete strategy. 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.

package com.effectivejava.classinterface;

import java.util.Arrays;

import java.util.Comparator;

/**

* @author Kaibo

*

*/

public class StringLengthComparator implements Comparator<String> {

public static final StringLengthComparator INSTANCE = new StringLengthComparator();

private StringLengthComparator() {

}

/*

* override the super class key method.

*/

public int compare(String s1, String s2) {

return s1.length() - s2.length();

}

public static void main(String[] args) {

String[] a = new String[] { "I", "This", "a", "is" };

System.out.println("a origin values:");

printStringArray(a);

System.out.println("b sorted values:");

Arrays.sort(a, StringLengthComparator.INSTANCE);

for (int i = 0, len = a.length; i < len; i++)

System.out.println(a[i]);

System.out.println();

String[] b = new String[] { "He", "is", "a", "programmer" };

System.out.println("b origin values:");

printStringArray(b);

System.out.println("b sorted values:");

System.out.println();

// implement the compartor strategy by anounymous class

Arrays.sort(b, new Comparator<String>() {

public int compare(String s1, String s2) {

return s1.length() - s2.length();

}

});

}

private static void printStringArray(String[] strs) {

for (int i = 0, len = strs.length; i < len; i++)

System.out.println(strs[i]);

}

}

Note

  1. Please give a field a discriptive name for the specific implementation.
  2. The anonymous class may create a new instance for each invoking.
  3. When a concrete strategy is designed for repeated use, it is generally implemented as a private static member class and exported in a public static final field whose type is the strategy interface instead of expose it to the public directly.

/**

*

*/

package com.effectivejava.classinterface;

import java.io.Serializable;

import java.util.Comparator;

/**

* @author Kaibo

*

*/

// Exporting a concrete strategy

class Host {

private static class StrLenCmp implements Comparator<String>, Serializable {

private static final long serialVersionUID = 1L;

public int compare(String s1, String s2) {

return s1.length() - s2.length();

}

}

// Returned comparator is serializable

public static final Comparator<String> STRING_LENGTH_COMPARATOR = new StrLenCmp();

// Bulk of class omitted

}

Effective Java 21 Use function objects to represent strategies的更多相关文章

  1. Effective Java 52 Refer to objects by their interfaces

    Principle If appropriate interface types exist, then parameters, return values, variables, and field ...

  2. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  3. 《Effective Java》读书笔记 - 4.类和接口

    Chapter 4 Classes and Interfaces Item 13: Minimize the accessibility of classes and members 一个好的模块设计 ...

  4. Effective Java Chapter4 Classes and Interface

    MInimize the accessibility of classes and members 这个叫做所谓的 information hiding ,这么做在于让程序耦合度更低,增加程序的健壮性 ...

  5. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  6. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  7. Effective Java 第三版——21. 为后代设计接口

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java通俗理解(持续更新)

    这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...

  9. Effective Java 第三版——10. 重写equals方法时遵守通用约定

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

随机推荐

  1. [python]新手写爬虫v2.5(使用代理的异步爬虫)

    开始 开篇:爬代理ip v2.0(未完待续),实现了获取代理ips,并把这些代理持久化(存在本地).同时使用的是tornado的HTTPClient的库爬取内容. 中篇:开篇主要是获取代理ip:中篇打 ...

  2. Android 学习笔记之AndBase框架学习(三) 使用封装好的函数完成Http请求..

    PS:踏踏实实走好每一步... 学习内容: 1.使用AndBase框架实现无参Http Get请求... 2.使用AndBase框架实现有参Http Post请求... 3.使用AndBase框架实现 ...

  3. 移动前端页面与Chrome的远程真机调试

    一年不见,博客园都长草啦...... 前几日刚入手新手机小米5,系统真心流畅呀.为啥要买小米5呢,因为要提高生产力呀,好好玩移动前端开发呀哈哈哈 那么问题来了,要怎么调试手机上的前端页面呢? 很久很久 ...

  4. 数论 - 欧拉函数模板题 --- poj 2407 : Relatives

    Relatives Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 11372   Accepted: 5544 Descri ...

  5. DataBase --- Intellij IDEA 14.1.4使用Java连接SQL Server教程

    Java连接数据库的方法大体分为两种:正向连接和反向连接.反向连接需要编译器提供相关的插件来支持,目前主流的java IDE都支持反向连接.这里主要对正向连接做一个经验总结. 一.数据库的配置 1.新 ...

  6. for循环的嵌套,for循环的穷举迭代

    for循环的嵌套            输入一个正整数,求阶乘的和 嵌套            Console.Write("请输入一个正整数:");            int ...

  7. TreeBuilder科学的树创建器

    public static class TreeBuilder { public static List<dynamic> Build(IEnumerable<dynamic> ...

  8. Android入门:Activity四种启动模式

    一.启动模式介绍 启动模式简单地说就是Activity启动时的策略,在AndroidManifest.xml中的标签的android:launchMode属性设置: 启动模式有4种,分别为standa ...

  9. MySQL SQL模式匹配

    MySQL提供标准的SQL模式匹配,SQL模式匹配允许你使用“_”匹配任何单个字符,而“%”匹配任意数目字符(包括零字符).. 关于SQL模式匹配:http://dev.mysql.com/doc/r ...

  10. 初学Java9:学习Mybatis时报错:Parameter 'name' not found. Available parameters are [1, 0, param1, param2]

    报错-->Parameter 'name' not found. Available parameters are [1, 0, param1, param2] 百度找到这篇文章完成修改 htt ...