Java Design Patterns

This commit is contained in:
Kunwar
2022-04-09 21:20:17 +05:30
parent cf9f87e82f
commit 03b7e798e9
6 changed files with 107 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public class Circle implements Shape {
@Override
public void drawShape() {
System.out.println("The shape is: Circle");
}
}

View File

@@ -0,0 +1,29 @@
package javadevjournal.design.structural.decorator;// DecoratorPatternDemo.java
/**
* @author Kunwar
*/
public class DecoratorPatternDemo {
public static void main(String[] args) {
// Creating objects of Shape interface
Shape circle = new Circle();
Shape rectangle = new Rectangle();
// Creating objects of decorated classes
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal fill");
circle.drawShape();
System.out.println("Rectangle with normal fill");
rectangle.drawShape();
System.out.println("\nCircle of red fill");
redCircle.drawShape();
System.out.println("\nRectangle of red fill");
redRectangle.drawShape();
}
}

View File

@@ -0,0 +1,12 @@
package javadevjournal.design.structural.decorator;// Class 1
/**
* @author Kunwar
*/
public class Rectangle implements Shape {
@Override
public void drawShape() {
System.out.println("The shape is: Rectangle");
}
}

View File

@@ -0,0 +1,27 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void drawShape() {
decoratedShape.drawShape();
//additional method to change the behavior of the shape object
shapeFill(decoratedShape);
}
/**
* This method will change the behavior of the shape object at runtime.
*
* @param decoratedShape
*/
private void shapeFill(Shape decoratedShape) {
System.out.println("Shape Fill color: Red");
}
}

View File

@@ -0,0 +1,8 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public interface Shape {
void drawShape();
}

View File

@@ -0,0 +1,19 @@
package javadevjournal.design.structural.decorator;
/**
* @author Kunwar
*/
public abstract class ShapeDecorator implements Shape {
//protected object of Shape Interface.
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
//calling the drawShape method on decoratedShape
public void drawShape() {
decoratedShape.drawShape();
}
}