Skip to content

Commit 78f3a09

Browse files
committed
added shape_decorator example
1 parent 7694c44 commit 78f3a09

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
//!--
2+
//! in this example we will decorate a shape with some color
3+
//! without alter (Change) shape class.
4+
//!--
5+
// Source: https://www.tutorialspoint.com/design_pattern/decorator_pattern.htm
6+
7+
// We're going to create a Shape interface and concrete classes implementing the Shape interface. We will then create an abstract decorator class ShapeDecorator implementing the Shape interface and having Shape object as its instance variable.
8+
// RedShapeDecorator is concrete class implementing ShapeDecorator.
9+
// DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate Shape objects.
10+
// Decorator Pattern UML Diagram
11+
12+
// Step 1
13+
// Create an interface.
14+
abstract class IShape {
15+
void draw();
16+
}
17+
18+
// Step 2
19+
// Create concrete classes implementing the same interface.
20+
class Rectangle implements IShape {
21+
@override
22+
void draw() => print("Shape: Rectangle");
23+
}
24+
25+
class Circle implements IShape {
26+
@override
27+
void draw() => print("Shape: Circle");
28+
}
29+
30+
// Step 3
31+
// Create abstract decorator class implementing the Shape interface.
32+
abstract class ShapeDecorator implements IShape {
33+
IShape decoratedShape;
34+
ShapeDecorator(IShape decoratedShape) : this.decoratedShape = decoratedShape;
35+
@override
36+
void draw() => decoratedShape.draw();
37+
}
38+
39+
// Step 4
40+
// Create concrete decorator class extending the ShapeDecorator class.
41+
class RedShapeDecorator extends ShapeDecorator {
42+
RedShapeDecorator(IShape decoratedShape) : super(decoratedShape);
43+
44+
@override
45+
void draw() {
46+
decoratedShape.draw();
47+
_setRedBorder(decoratedShape);
48+
}
49+
50+
void _setRedBorder(IShape decoratedShape) {
51+
print("Border Color: Red");
52+
}
53+
}
54+
55+
// Step 5
56+
// Use the main() to decorate Shape objects.
57+
void main(List<String> args) {
58+
IShape circle = Circle();
59+
IShape redCircle = RedShapeDecorator(Circle());
60+
IShape redRectangle = RedShapeDecorator(Rectangle());
61+
62+
print("Circle with normal border");
63+
circle.draw();
64+
65+
print("\nCircle of red border");
66+
redCircle.draw();
67+
68+
print("\nRectangle of red border");
69+
redRectangle.draw();
70+
}
71+
72+
// Step 6
73+
// Verify the output.
74+
75+
// Circle with normal border
76+
// Shape: Circle
77+
78+
// Circle of red border
79+
// Shape: Circle
80+
// Border Color: Red
81+
82+
// Rectangle of red border
83+
// Shape: Rectangle
84+
// Border Color: Red

0 commit comments

Comments
 (0)