Search code examples
javadelegation

How to delegate the implementation of one class in other class in Java?


I am trying to refactor util java class A(for example). It is composed of all static methods, but there are a lot of methods so i extracted few methods which are independent of each other and created a helper class B(Code Quality Analysis tool complains of having too any methods in this class) Now, I don't know how to make class B backward compatible? I have been asked to create a "method" in Class A and delegate the implementation of Class B in it. I don't understand how that can be done. I know we can achieve delegation through interfaces, and other design patterns in java. But these classes are really not complicated.

So how can this be done by creating a method?

    public class A{
    public static doSomething1();
    public static doSomething2();
    public static doSomething3();

    }

    public class B{
    public static doSomethingElse1();
    public static doSomethingElse2();
    public static doSomethingElse3();

    }

Solution

  • That is called the adapter pattern, and it is pretty simple. Create a method in class A:

    class A {
        ...
        public static doSomethingElse1() {
            B.doSomethingElse1();
        }
    }
    

    Which simply calls the same method in class B.

    Although this answers your question, it will not help you much. The best course of action would be to try and completely remove these utility classes, going for a more OO design, but without more details, it hard to say if that is possible.