mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-08-17 04:26:05 +00:00
docs: update delegation
This commit is contained in:
@@ -3,7 +3,9 @@ title: Delegation
|
|||||||
category: Behavioral
|
category: Behavioral
|
||||||
language: en
|
language: en
|
||||||
tag:
|
tag:
|
||||||
|
- Decoupling
|
||||||
- Delegation
|
- Delegation
|
||||||
|
- Object composition
|
||||||
---
|
---
|
||||||
|
|
||||||
## Also known as
|
## Also known as
|
||||||
@@ -13,7 +15,7 @@ tag:
|
|||||||
|
|
||||||
## Intent
|
## Intent
|
||||||
|
|
||||||
The Delegation pattern in Java allows an object to delegate one or more tasks to a helper object. It is a technique where an object expresses certain behavior but actually delegates responsibility for implementing that behavior to an associated helper object.
|
To allow an object to delegate responsibility for a task to another helper object.
|
||||||
|
|
||||||
## Explanation
|
## Explanation
|
||||||
|
|
||||||
@@ -27,6 +29,8 @@ Wikipedia says
|
|||||||
|
|
||||||
**Programmatic Example**
|
**Programmatic Example**
|
||||||
|
|
||||||
|
Let's consider a printing example.
|
||||||
|
|
||||||
We have an interface `Printer` and three implementations `CanonPrinter`, `EpsonPrinter` and `HpPrinter`.
|
We have an interface `Printer` and three implementations `CanonPrinter`, `EpsonPrinter` and `HpPrinter`.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@@ -59,8 +63,7 @@ public class HpPrinter implements Printer {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The `PrinterController` can be used as a `Printer` by delegating any work handled by this
|
The `PrinterController` can be used as a `Printer` by delegating any work handled by this interface to an object implementing it.
|
||||||
interface to an object implementing it.
|
|
||||||
|
|
||||||
```java
|
```java
|
||||||
public class PrinterController implements Printer {
|
public class PrinterController implements Printer {
|
||||||
@@ -78,8 +81,7 @@ public class PrinterController implements Printer {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Now on the client code printer controllers can print messages differently depending on the
|
Now on the client code printer controllers can print messages differently depending on the object they're delegating that work to.
|
||||||
object they're delegating that work to.
|
|
||||||
|
|
||||||
```java
|
```java
|
||||||
public class App {
|
public class App {
|
||||||
|
|||||||
Reference in New Issue
Block a user