Java编程思想中关于闭包的一个例子
2017-10-28 16:42
453 查看
Java编程思想中的一个例子,不是很理解使用闭包的必要性,如果不使用闭包,是不是有些任务就不能完成?继续探索。
package InnerClass; interface Incrementable { void increment(); } /** 被调1 */ // Very simple to just implement the interface class Callee1 implements Incrementable { private int i = 0; @Override public void increment() { i++; System.out.println("Callee1" + i); } } class MyIncrement { public void increment() { System.out.println("other operation"); } static void f(MyIncrement mi) { mi.increment(); } } // if your class must implement increment() in some other way, you must use an // inner class class Callee2 extends MyIncrement implements Incrementable { private int i = 0; public void increment() { super.increment(); i++; System.out.println("Callee2:" + i); } private class Closure implements Incrementable { public void increment() { System.out.println("内部类实现接口");//1.这句是我加的。 Callee2.this.increment();//2.既然想表达与外部类的不同,此处为何还要调用外部类的方法实现同一个功能,造成迷惑 } } Incrementable getCallbackReference() { return new Closure(); } } class Caller { private Incrementable callbarckReference; public Caller(Incrementable chb) { callbarckReference = chb; } void go() { callbarckReference.increment(); } } public class Callbacks { public static void main(String[] args) { Callee1 c1 = new Callee1(); Callee2 c2 = new Callee2(); MyIncrement.f(c2); Caller caller1 = new Caller(c1); Caller caller2 = new Caller(c2.getCallbackReference()); caller1.go(); caller1.go(); caller2.go(); caller2.go(); } }
相关文章推荐
- 关于Java的RMI编程的一个简单的例子
- 关于Java的RMI编程的一个简单的例子
- 关于《Java 编程思想》第四版第十五章“泛型”逆变例子的疑惑
- 自制简单的Java下载器——来自《Java高级编程》的一个关于线程的例子(带上部分注释)
- 自制简单的Java下载器——来自《Java高级编程》的一个关于线程的例子(带上部分注释)
- java编程思想-关于final
- Java网络编程(32):一个非阻塞I/O的例子
- java编程思想3感悟(2)---每个对象都有一个接口(方法)
- 关于Java、Python、Go编程思想的不同
- 征求关于java编程思想的教学材料(教学设计文档、PPT等)
- [原创][Java]由一个Java编程思想书中线程间协作的例子想到的
- 一个饲养员给动物喂食物的例子体现JAVA中的面向对象思想,接口(抽象类)的用处
- Java编程思想-注解生成外部例子代码
- java.NIO网络编程很不错的一个例子
- 通过一个很实用的例子让你学会T-SQL编程的基本语法和思想
- Java网络编程从入门到精通(32):一个非阻塞I/O的例子
- java编程思想中关于多态性的描述
- Java 多线程编程之五:一个理解 wait() 与 notify() 的例子
- 一个例子体现JAVA中的面向对象思想,接口(抽象类)的用处
- 关于Java Annotation的一个例子