Skip to content

Commit aa2bb26

Browse files
committed
Add Decorator Pattern
1 parent 27dedb6 commit aa2bb26

File tree

8 files changed

+46
-15
lines changed

8 files changed

+46
-15
lines changed
File renamed without changes.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class Circle implements Shape {
2+
public void draw (){
3+
System.out.println("Shape : Circle");
4+
}
5+
}

Design patterns/Structural Pattern/Decorator/DecoratorDemo.java

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,18 @@
22
1)Object at central is called Component and one wrapping component is call Decorator
33
and one wrapping decorator is called Decorator
44
2)Attach additional responsibilities to an object dynamically.
5+
Decorators provide a flexible alternative to subclassing for extending functionality
56
*/
67

7-
abstract class ok
8-
{
9-
abstract void m1();
10-
void m2()
11-
{
12-
System.out.println("This is data from m2");
13-
}
14-
}
15-
class DecoratorDemo extends ok {
16-
void m1()
17-
{
18-
System.out.println("This is frmo m1");
19-
}
8+
class DecoratorDemo{
209
public static void main(String[] args) {
21-
DecoratorDemo obj = new DecoratorDemo();
22-
obj.m2();
10+
Shape circle = new Circle();
11+
System.out.println("\nCircle with normal boredr");
12+
circle.draw();
13+
14+
circle = new RedShapeDecorator(circle);
15+
System.out.println("\nCircle with Red boredr");
16+
circle.draw();
17+
2318
}
2419
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class RedShapeDecorator extends ShapeDecorator {
2+
public RedShapeDecorator(Shape decoratedShape) {
3+
super(decoratedShape);
4+
}
5+
6+
private void setRedBorder(Shape decoratedShape){
7+
System.out.println("Border Color : Red");
8+
}
9+
public void draw(){
10+
decoratedShape.draw();
11+
setRedBorder(decoratedShape);
12+
}
13+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
interface Shape {
2+
void draw();
3+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
public abstract class ShapeDecorator implements Shape {
2+
protected Shape decoratedShape ;
3+
public ShapeDecorator(Shape decoratedShape){
4+
this.decoratedShape = decoratedShape;
5+
}
6+
7+
public void draw(){
8+
this.decoratedShape.draw();
9+
}
10+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class Square implements Shape {
2+
public void draw(){
3+
System.out.println("Shape : Square");
4+
}
5+
}
23.4 KB
Loading

0 commit comments

Comments
 (0)