What is the difference between “Forwarding” and “Delegation” ?

The difference between “forwarding” and “delegation”

In object-oriented programming, “forwarding” and “delegation” are often confused.

They both share the point that “there are two objects, and when you call the function ‘foo’ of object A, the function ‘foo’ of object B is called inside the function”

The difference is that “After the function foo of object B is called, which object’s function bar, object A or object B, will be called

Forwarding

class B {
    func foo() {
        this.bar()
    }
    func bar() {
        print("B bar")
    }
}

class A {
    func A(B b) {
        this.b = b
    }
    func foo() {
        this.b.foo()
    }
    func bar() {
        print("A bar")
    }
}

a = new A(new B())
a.foo()

// "B bar"

When you call the foo function of A, the foo function of B is called inside the function and the bar function of B is called beyond that.

Delegation

class B {
    func foo() {
        this.delegate.bar()
    }
    func bar() {
        print("B bar")
    }
}

class A {
    func A(B b) {
        this.b = b
        this.b.delegate = this;
    }
    func foo() {
        this.b.foo()
    }
    func bar() {
        print("A bar")
    }
}

a = new A(new B())
a.foo()

// "A bar"

In the constructor of A, the delegate property of B is set to this (=A).

When we call the foo function of A, the foo function of B is called inside the function, and beyond that the bar function of A (=this. delegate)’s bar function is called.

Delegation by Inheritance

Delegation can also be achieved through inheritance.

class B {
    func foo() {
        this.bar()
    }
    func bar() {
        print("B bar")
    }
}

class A extends B {
    func foo() {
        super.foo()
    }
    func bar() {
        print("A bar")
    }
}

a = new A()
a.foo()

// "A bar"