Easy Tutorial
❮ Docker Use Container Create Image Android Tutorial Git Repo Operate ❯

Delegation Pattern

Category Programming Techniques

The delegation pattern is a fundamental technique in software design patterns. In the delegation pattern, two objects are involved in handling the same request, and the object receiving the request delegates it to another object for processing. The delegation pattern is a basic technique, and many other patterns, such as the state pattern, strategy pattern, and visitor pattern, essentially use the delegation pattern in more specific situations. The delegation pattern allows us to replace inheritance with composition, and it also enables us to simulate mixins.

Simple Java Example

In this example, the class simulating a printer, Printer, has an instance of a dot-matrix printer, RealPrinter. The method print() of Printer is handed over to the method print() of RealPrinter.

class RealPrinter { // the "delegate"
     void print() { 
       System.out.print("something"); 
     }
 }

 class Printer { // the "delegator"
     RealPrinter p = new RealPrinter(); // create the delegate 
     void print() { 
       p.print(); // delegation
     } 
 }

 public class Main {
     // to the outside world it looks like Printer actually prints.
     public static void main(String[] args) {
         Printer printer = new Printer();
         printer.print();
     }
 }

Complex Java Example

By using interfaces, delegation can be type-safe and more flexible. In this example, category C can delegate to category A or category B, and category C has a method that allows it to choose between category A or category B. Since category A or category B must implement the methods specified by the interface I, the delegation here is type-safe. This example shows the disadvantage of delegation, which is the need for more code.

interface I {
     void f();
     void g();
 }

 class A implements I {
     public void f() { System.out.println("A: doing f()"); }
     public void g() { System.out.println("A: doing g()"); }
 }

 class B implements I {
     public void f() { System.out.println("B: doing f()"); }
     public void g() { System.out.println("B: doing g()"); }
 }

 class C implements I {
     // delegation
     I i = new A();

     public void f() { i.f(); }
     public void g() { i.g(); }

     // normal attributes
     public void toA() { i = new A(); }
     public void toB() { i = new B(); }
 }


 public class Main {
     public static void main(String[] args) {
         C c = new C();
         c.f();     // output: A: doing f()
         c.g();     // output: A: doing g()
         c.toB();
         c.f();     // output: B: doing f()
         c.g();     // output: B: doing g()
     }
 }

>

Source: https://zh.wikipedia.org/wiki/Delegation_Pattern

❮ Docker Use Container Create Image Android Tutorial Git Repo Operate ❯