Java equivalent of Cocoa delegates / Objective-C informal protocols?

后端 未结 3 1613
粉色の甜心
粉色の甜心 2021-02-02 00:32

What is the Java equivalent of Cocoa delegates?

(I understand that I can have an interface passed to a class, and have that class call the appropriate methods, but I\'m

3条回答
  •  余生分开走
    2021-02-02 01:04

    Best analog to an informal protocol I can think of is an interface that also has an adapter class to allow implementers to avoid implementing every method.

    public class MyClass {
    
        private MyClassDelegate delegate;
    
        public MyClass () {
    
        }
    
        // do interesting stuff
    
        void setDelegate(MyClassDelegate delegate) {
            this.delegate = delegate;
        }
    
        interface MyClassDelegate {
            void aboutToDoSomethingAwesome();
            void didSomethingAwesome();
        }
    
        class MyClassDelegateAdapter implements MyClassDelegate {
    
            @Override
            public void aboutToDoSomethingAwesome() {
                /* do nothing */
            }
    
            @Override
            public void didSomethingAwesome() {
                /* do nothing */
            }
        }
    }
    

    Then someone can come along and just implement the stuff they care about:

    class AwesomeDelegate extends MyClassDelegateAdapter {
    
        @Override
        public void didSomethingAwesome() {
            System.out.println("Yeah!");
        }
    }
    

    Either that, or pure reflection calling "known" methods. But that's insane.

提交回复
热议问题