Q: What are design patterns
Slowly: Design pattern is a solution for common scenarios in system service design, which can solve common problems encountered in the development of functional logic. Design pattern is not limited to the final implementation scheme, but in this conceptual pattern, to solve the code logic problems in system design.
Q: What is decorator mode
Slowly: Decorators meet the single responsibility principle, can extend functional logic in their own decorator classes without affecting the main class, and can add and remove this logic at run time as needed. This design pattern is a structural pattern that acts as a wrapper around existing classes.
Small Q: I understand, but how to achieve it?
Slowly: Let’s look at an example.
public interface Shape {
void draw(a);
}
Copy the code
public class Rectangle implement Shape {
@Override
public void draw(a) {
System.out.println("Shape: Rectangle"); }}Copy the code
public class Circle implements Shape {
@Override
public void draw(a) {
System.out.println("Shape: Circle"); }}Copy the code
Shape interface to implement the abstract class, to enhance the function of the original class.
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
public void draw(a) { decoratedShape.draw(); }}Copy the code
Create an entity class for enhancement
public class ReadShapeDecorator extends ShapeDecorator {
public ReadShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw(a) {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape) {
System.out.println("Border Color: Red"); }}Copy the code
test
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape circle = new Circle();
ShapdeDecorator redCircle = new RedShapeDecorator(newCircle); circle.draw(); redCircle.draw(); }}Copy the code
Q: What’s the difference between a decorator and an adapter?
Slowly: Decorators need to be wrapped in a class to extend their functionality, while adapters need to be wrapped in a class to make them easier to call and expose methods suitable for others to call.