Java

Usage examples: The Decorator is pretty standard in Java code, especially in code related to streams.

Here are some examples of Decorator in core Java libraries:

Identification: Decorator can be recognized by creation methods or constructors that accept objects of the same class or interface as a current class.

Encoding and compression decorators

This example shows how you can adjust the behavior of an object without changing its code.

Initially, the business logic class could only read and write data in plain text. Then we created several small wrapper classes that add new behavior after executing standard operations in a wrapped object.

The first wrapper encrypts and decrypts data, and the second one compresses and extracts data.

You can even combine these wrappers by wrapping one decorator with another.

decorators

decorators/DataSource.java: A common data interface, which defines read and write operations

package refactoring_guru.decorator.example.decorators;

public interface DataSource {
    void writeData(String data);

    String readData();
}

decorators/FileDataSource.java: Simple data reader-writer

decorators/DataSourceDecorator.java: Abstract base decorator

decorators/EncryptionDecorator.java: Encryption decorator

decorators/CompressionDecorator.java: Compression decorator

Demo.java: Client code

OutputDemo.txt: Execution result

Last updated