Java - Alternatives to forcing subclass to have a static method

前端 未结 5 1477

I often find I want to do something like this:

class Foo{
public static abstract String getParam();
}

To force a subclasses of Foo to retur

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 23:10

    You can use the factory pattern to allow the system to create 'data' instances first, and create 'functional' instances later. The 'data' instances will contain the 'mandatory' getters that you wanted to have static. The 'functional' instances do complex parameter validation and/or expensive construction. Of course the parameter setter in the factory can also so preliminary validation.

    public abstract class Processor { /*...*/ }
    
    public interface ProcessorFactory {
        String getName(); // The  mandatory getter in this example
    
        void setParameter(String parameter, String value);
    
        /** @throws IllegalStateException when parameter validation fails */
        Processor construct();
    }
    
    public class ProcessorA implements ProcessorFactory {
        @Override
        public String getName() { return "processor-a"; }
    
        @Override
        public void setParameter(String parameter, String value) {
            Objects.requireNonNull(parameter, "parameter");
            Objects.requireNonNull(value, "value");
            switch (parameter) {
                case "source": setSource(value); break;
                /*...*/
                default: throw new IllegalArgumentException("Unknown parameter: " + parameter);
            }
        }
    
        private void setSource(String value) { /*...*/ }
    
        @Override
        public Processor construct() {
            return new ProcessorAImpl();
        }
    
        // Doesn't have to be an inner class. It's up to you.
        private class ProcessorAImpl extends Processor { /*...*/ }
    }
    

提交回复
热议问题