Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created February 17, 2018 06:00
Show Gist options
  • Save jigewxy/dfd5831513ee05522a78a279b3c629a7 to your computer and use it in GitHub Desktop.
Save jigewxy/dfd5831513ee05522a78a279b3c629a7 to your computer and use it in GitHub Desktop.
Decorator design pattern
package com.company;
interface Shape{
void draw();
}
class Circle implements Shape{
public void draw()
{
System.out.println("Draw a Circle");
}
}
abstract class ShapeDecorator implements Shape{
Shape decoratedShape;
ShapeDecorator(Shape s){
this.decoratedShape = s;
}
public void draw(){
decoratedShape.draw();
};
}
class RedCircle extends ShapeDecorator{
RedCircle(Shape s)
{
super(s);
}
@Override
public void draw(){
decoratedShape.draw();
drawRedBorder();
}
public void drawRedBorder(){
System.out.println("Draw a Red Border for the circle");
}
}
public class DecoratorDemo {
public static void main(String[] args){
Shape circle = new Circle();
circle.draw();
Shape redcircle = new RedCircle(circle);
redcircle.draw();
}
}
/*
* 1. ShapeDecorator class should be an abstract class, which implements shape interface;
* 2. ShapeDecorator should accept a shape instance as input for constructor.
* 3. concrete decorator class should extends the ShapeDecorator and override the decorated method.
* By doing so, we can add more functionalities to Circle() object, without changing its original class definition.
*
*
* */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment