Sobes.tech
Junior — Middle

Explain the principle of using the Wrapper pattern in components and its purpose.

sobes.tech AI

Answer from AI

The Wrapper pattern in components is used to add additional functionality to an existing object without modifying its code. This is achieved by creating a new class that contains a reference to the original object and overrides or extends its behavior.

Purpose of the Wrapper pattern:

  • Encapsulation of additional logic (e.g., logging, permission checks, caching).
  • Changing the interface or adapting the object to a different interface.
  • Simplifying or restricting access to the functionality of the original object.

Example in Java:

interface Service {
    void execute();
}

class RealService implements Service {
    public void execute() {
        System.out.println("Executing main logic");
    }
}

class ServiceWrapper implements Service {
    private Service wrapped;

    public ServiceWrapper(Service wrapped) {
        this.wrapped = wrapped;
    }

    public void execute() {
        System.out.println("Before execution");
        wrapped.execute();
        System.out.println("After execution");
    }
}

// Usage:
Service service = new ServiceWrapper(new RealService());
service.execute();

In this example, ServiceWrapper adds behavior before and after calling the execute method of the original object.