Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Design Patterns
|
Decorator
References
Example
The
Component
The
Concrete Component
The
Decorator
The
Concrete Decorator
A simple class to test the
Decorator
design pattern
References
Definition: (
source:
http://en.wikipedia.org/wiki/Decorator_pattern
)
The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time.
Class diagram: (
source:
http://en.wikipedia.org/wiki/Decorator_pattern
)
Example
The
Component
:
public interface Logger { void log(); }
The
Concrete Component
:
public class FileLogger implements Logger { public void log() { System.out.println("FileLogger-log"); } }
The
Decorator
:
public abstract class CustomLogger implements Logger { private final Logger logger = new FileLogger(); public void log() { logger.log(); } }
The
Concrete Decorator
:
public class AuditLogger extends CustomLogger { public void log() { super.log(); System.out.println("AuditLogger-log"); } }
A simple class to test the
Decorator
design pattern:
public class DecoratorPatternTest { public static void main(String[] args) { // create the decorator final Logger logger = new AuditLogger(); // call the decorated method logger.log(); } }
© 2010-2022
mti
tek