javareflectionwrapperdelegationdynamic-proxy

create a wrapper class with additional features in java


I want to create a wrapper class over another class so that it hides the functionality of wrapped class and also the wrapper provides certain methods of its own.

For example, lets say we have class A as

public class A{
    void method1(){ ... do something ... }
    void method2(){ ... do something ... }
    void method3(){ ... do something ... }
}

Now I want another class B which wraps class A, so that it has its own methods, and also if someone asks method of class A, it should delegate it to class A.

public class B{
     // if someone asks method1() or method2() or method3() ... it should delegate it to A
     
     // and also it has own methods
     void method4(){ ... do something ... }
     void method5(){ ... do something ... }
}

I can't use inheritance (i.e B extends A) because its not easy with my use case (where A has concrete constructor with some parameters which we can't get ... but we can get the object of A).

I can't simply delegate each function in A using object of A (because there are several functions in A)

Is there any other way to obtain class B with said restrictions?

Important Note: Class A is handled by someone else. We can't change any part of it.


Solution

  • What you have described is a Decorator pattern coined by GOF. There is plenty of sources on the Internet about it. It is similar to the Proxy pattern (as in the answer of Pavel Polivka) but the intent is different. You need the Decorator pattern:

    Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. sourcemaking.com

    As you have written in a comment

    class A inherits from single interface containing several methods

    I assume A implements AIntf and contains all the methods you want.

    public class BDecorator implements AIntf {
        private A delegate;
    
        private BDecorator(A delegate) {
            this.delegate = delegate;
        }
    
        void method1(){ delegate.method1(); }
        // ...
    
        void method4(){ /* something new */ }
    
    

    There are several functions in A, and I don't want to do tedious work of writing each method explicitly in B.

    Java is a verbose language. However, you don't need to do this by hand, every decent IDE provides automatic generation of delegate methods. So it will take you 5 seconds for any amount of methods.

    The class A is not in my control, I mean someone might update its method signatures, In that case I need to watch over class A and made changes to my class B.

    If you create B you are responsible for it. You at least notice if anything changed. And once again, you can re-generate the changed method with the help of an IDE in an instant.