Decorator Pattern of Design Patterns

The Decorator Pattern allows adding new functionality to an existing object without changing its structure. This type of design pattern is a structural pattern, which acts as a wrapper around an existing class.

This pattern creates a decorated class that wraps the original class and provides additional functionality while maintaining the integrity of the class's method signatures.

We demonstrate the usage of the decorator pattern through the following example. Among them, we will decorate a shape with a different color without changing the shape class.


Usage scenarios:  1. Extend the functionality of a class. 2. Dynamically add functions and dynamically cancel.


/**
 * Created by qiuyunjie on 2018/4/19.
 */
interface Shape{
    void  draw();
}

class ZhengFang implements Shape{

    @Override
    public void draw() {
        System.out.println("I am a square");
    }
}

class SanJiao implements Shape{

    @Override
    public void draw() {
        System.out.println("I am a triangle");
    }
}

abstract class ZhuangShi implements Shape{

    protected Shape zhuangshi ;

    public ZhuangShi(Shape zhuangshi){
        this.zhuangshi = zhuangshi;
    }

    public void draw(){
        zhuangshi.draw();
    }
}

class Red extends ZhuangShi{

    public Red(Shape zhuangshi) {
        super(zhuangshi);
    }

    @Override
    public void draw() {
        zhuangshi.draw();
        Zhuangshi(zhuangshi);
    }

    private void Zhuangshi(Shape zhuangshi){
        System.out.println("Added red");
    }
}

class Green extends ZhuangShi{

    public Green(Shape zhuangshi) {
        super(zhuangshi);
    }

    @Override
    public void draw() {
        zhuangshi.draw();
        Zhuangshi(zhuangshi);
    }

    public void Zhuangshi(Shape zhuangshi){
        System.out.println("Added green");
    }
}

public class Client {
    public static void main(String[] args){
        Shape SanJiao = new Red(new SanJiao());
        SanJiao.draw();

        Shape ZhengFang = new Green(new ZhengFang());
        ZhengFang.draw();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324606107&siteId=291194637