How to 'wrap' two classes with identical methods?

前端 未结 6 725
萌比男神i
萌比男神i 2021-02-15 10:50

I have to handle two classes with identical methods but they don\'t implement the same interface, nor do they extend the same superclass. I\'m not able / not allowed to change t

6条回答
  •  误落风尘
    2021-02-15 11:27

    A better solution would be to create an interface to represent the unified interface to both classes, then to write two classes implementing the interface, one that wraps an A, and another that wraps a B:

    public interface SomethingWrapper {
        public String getValueOne();
        public void setValueOne(String valueOne);
        public String getValueTwo();
        public void setValueTwo(String valueTwo);
    };
    
    public class SomethingAWrapper implements SomethingWrapper {
    
        private SomethingA someA;
    
        public SomethingWrapper(SomethingA someA) {
            this.someA = someA;
        }
    
        public String getValueOne() {
            return this.someA.getValueOne();
        }
    
        public void setValueOne(String valueOne) {
            this.someA.setValueOne(valueOne);
        }
    
        public String getValueTwo() {
            return this.someA.getValueTwo();
        }
    
        public void setValueTwo(String valueTwo) {
            this.someA.setValueTwo(valueTwo);
        }
    };
    

    and then another class just like it for SomethingBWrapper.

提交回复
热议问题