zoukankan      html  css  js  c++  java
  • Java编程思想中关于闭包的一个例子

    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();
        }
    }
  • 相关阅读:
    剑指Offer面试题:26.字符串的排列
    剑指Offer面试题:25.二叉搜索树与双向链表
    使用VS2013分析DMP文件
    目的 存在 问题 价值
    thinking models--基于事实和全方位思考
    目的-哲学解释
    亚里士多德.四因说
    存在与目的 人类与上帝
    我用过的数据库 sqlite realm mysql coredata
    swift Existential Container witness table
  • 原文地址:https://www.cnblogs.com/Sabre/p/7747331.html
Copyright © 2011-2022 走看看