Posted By

kolepep on 03/01/16


Tagged

java pattern


Versions (?)

Delegation pattern


 / Published in: Java
 

URL: https://en.wikipedia.org/wiki/Helper_object

In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object.

  1. interface I {
  2. void f();
  3. void g();
  4. }
  5.  
  6. class A implements I {
  7. public void f() { System.out.println("A: doing f()"); }
  8. public void g() { System.out.println("A: doing g()"); }
  9. }
  10.  
  11. class B implements I {
  12. public void f() { System.out.println("B: doing f()"); }
  13. public void g() { System.out.println("B: doing g()"); }
  14. }
  15.  
  16. // changing the implementing object in run-time (normally done in compile time)
  17. class C implements I {
  18. I i = null;
  19. // delegation
  20. public C(I i){ setI(i); }
  21. public void f() { i.f(); }
  22. public void g() { i.g(); }
  23.  
  24. // normal attributes
  25. public void setI(I i) { this.i = i; }
  26. }
  27.  
  28. public class Main {
  29. public static void main(String[] arguments) {
  30. C c = new C(new A());
  31. c.f(); // output: A: doing f()
  32. c.g(); // output: A: doing g()
  33. c.setI(new B());
  34. c.f(); // output: B: doing f()
  35. c.g(); // output: B: doing g()
  36. }
  37. }

Report this snippet  

You need to login to post a comment.