Dynamic method dispatch

前端 未结 2 1049
春和景丽
春和景丽 2021-01-24 17:10

There is lot of info on Dynamic dispatch in the internet, I feel like a chicken as I am not able to implement it. Please help me. Here is what I am trying to do.



        
2条回答
  •  失恋的感觉
    2021-01-24 17:34

    You could create a Dispatcher interface which simply defines a method dispatch(String) (or whatever you try to achieve). The base class (ClassB) uses a NullPattern which implements the interface while the child class (ClassC) implements the interface according your needs.

    The interface is quite simple:

    public interface Dispatcher
    {
        public void dispatch(String message);
    }
    

    The NullPattern is implemented like this:

    public class NullDispatcher implements Dispatcher
    {
        public void dispatch(String message)
        {
            // do nothing
        }
    }
    

    ClassB should be modified like this:

    public class ClassB
    {
        private Dispatcher dispatcher;
    
        public ClassB()
        {
            dispatcher = new NullDispatcher();
        }
    
        public void setDispatcher(Dispatcher dispatcher)
        {
            // change this to your needs
            if (dispatcher == null)
                dispatcher = new NullDispatcher();
            else
                this.dispatcher = dispatcher;
        }
    
        @Test
        public void myTest()
        {
            ClassA a = new ClassA();
            a.createRequest();
            String test = a.getResponse();
    
            dispatcher.dispatch(test);
        }
    }
    

    Here a new Dispatcher can be set using the setDispatcher(Dispatcher) method. This dispatcher will be used in myTest to dispatch the result of a.getResponse().

    The extending class just needs to set a specific implementation of the Dispatcher. F.e. to print the response to the console you could implement a ConsoleDispatcher like this:

    public class ConsoleDispatcher implements Dispatcher
    {
        public void dispatch(String message)
        {
            System.out.println(message);
        }
    }
    

    To use the ConsoleDispatcher instead of the NullDispatcher in ClassC you might use a code similar to:

    public class ClassC extends ClassB
    {
        public ClassC()
        {
            this.setDispatcher(new ConsoleDispatcher());
        }
    }
    

    As ClassC extends ClassB you will have access to myTest which uses the defined dispatcher to dispatch the message accordingly.

    HTH

提交回复
热议问题