• Принцип закрытости/открытости, как добавить новый метод?

    @doctrine
    Вот два примера. Но все зависит от конкретного случая

    public interface EngineStartOperation {
        void start();
    }
    
    public interface EngineStopOperation {
        void stop();
    }
    
    public interface NewWhatEverMethod {
        void whatEver();
    }
    
    
    
    
    
    public class Engine implements EngineStartOperation, EngineStopOperation {
        @Override
        public void start() {
            // existing method
        }
    
        @Override
        public void stop() {
            // existing method
        }
    }
    
    
    
    public class WhatEverEngine1 implements NewWhatEverMethod, EngineStartOperation, EngineStopOperation {
        @Override
        public void start() {
    
        }
    
        @Override
        public void stop() {
    
        }
    
        @Override
        public void whatEver() {
            // new  logic here
        }
    }
    
    
    public class WhatEverEngine2 implements NewWhatEverMethod, EngineStartOperation, EngineStopOperation {
        private final Engine engine;
    
        public WhatEverEngine2(final Engine engine) {
            this.engine = engine;
        }
    
        @Override
        public void start() {
            engine.start();
        }
    
        @Override
        public void stop() {
            engine.stop();
        }
    
        @Override
        public void whatEver() {
            // new  logic here
        }
    }
    Ответ написан
    Комментировать