Design pattern for default implementation with empty methods

前端 未结 9 1362
余生分开走
余生分开走 2021-02-02 11:32

Is there a specific design pattern that describes the scenario where a non-abstract default implementation is provided that implements all or some of the method

9条回答
  •  孤街浪徒
    2021-02-02 11:56

    Great question.

    I have started using NoOp as a class name prefix for this pattern. It's short, clear, and not overloaded (like Empty [contains nothing?], Null [Null Object pattern, which is different?], Abstract [Does it provide some implementation?], or Base [Does it provide some implementation?]).

    I may write this style of class when I have a third-party API which provides "Hooks" for isntrumentation during a complex operation. Consider the following two classes provided by a library:

    public class LongRunningActionRunner {
        public void runSomethingLong(DecisionListener cdh) {
            // ...
        }
    }
    
    public interface DecisionListener {
        public void beforeFooHook();
        public void afterFooHook();
        public void beforeBarHook();
        public void afterBarHook();
        public void beforeBazHook();
        public void afterBazHook();
    }
    

    In this case, you might right a class using this pattern like this:

    public class NoOpDecisionListener implements DecisionListener {
        @Override public Something beforeFooHook() {}
        @Override public Something afterFooHook() {}
        @Override public Something beforeBarHook() {}
        @Override public Something afterBarHook() {}
        @Override public Something beforeBazHook() {}
        @Override public Something afterBazHook() {}
    }
    

提交回复
热议问题