Skip to content

Instantly share code, notes, and snippets.

@alincc
Last active February 2, 2016 16:56
Show Gist options
  • Save alincc/28e861b1deb94df8d933 to your computer and use it in GitHub Desktop.
Save alincc/28e861b1deb94df8d933 to your computer and use it in GitHub Desktop.
Java Decorator sample
// Decorator
// Test it here: https://www.compilejava.net/
// Source: https://sourcemaking.com/design_patterns/decorator
// Intent: Attach additional responsibilities to an object dynamically
interface Widget {
void draw();
}
class TextWidget implements Widget {
public TextWidget(int x, int y){
}
public void draw(){
System.out.println("TextWidget");
}
}
abstract class Decorator implements Widget {
Widget widget;
public Decorator(Widget w){
widget = w;
}
public void draw(){
widget.draw();
}
}
class BorderDecorator extends Decorator {
public BorderDecorator(Widget w){
super(w);
}
public void draw(){
super.draw();
System.out.println("BorderDecorator");
}
}
public class Main
{
public static void main(String[] args)
{
Widget w = new BorderDecorator(new TextWidget(10,10));
w.draw();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment