美文网首页
装饰模式

装饰模式

作者: 金煜博 | 来源:发表于2021-05-02 08:40 被阅读0次

什么是装饰模式?

在不改变对象已有功能的前提下,对已有对象进行功能的扩展。

示例场景描述

房子为毛呸房,需对毛呸房进行装修,先装地板在装门。

示例图

图片.png

示例代码

1.创建抽象功能类

public class DecoratorBehavior {
    public void decoratorHouse(){
    }
}

2.创建被装饰类

public class RoughHome extends DecoratorBehavior {
    @Override
    public void decoratorHouse() {
        System.out.println("1>>>>>>>>>>>>>>>购买毛呸房");
    }
}

3.创建抽象装饰类

public abstract class DecoratorWork extends DecoratorBehavior{
    protected  DecoratorBehavior decoratorBehavior;

    public DecoratorWork(DecoratorBehavior decoratorBehavior) {
        this.decoratorBehavior = decoratorBehavior;
    }

    public DecoratorWork() {

    }

    @Override
    public void decoratorHouse() {
        if(decoratorBehavior!=null){
            decoratorBehavior.decoratorHouse();
        }
    }
}

4.创建具体装饰类-地板和门

public class Floor extends  DecoratorWork{
    public Floor(DecoratorBehavior decoratorBehavior) {
        super(decoratorBehavior);
    }

    public Floor() {
    }

    @Override
    public void decoratorHouse() {
        super.decoratorHouse();
        System.out.println("2>>>>>>>>>>>>>>>>>>安装地板");
    }
}
 public class Door extends DecoratorWork{

    public Door(DecoratorBehavior decoratorBehavior) {
        super(decoratorBehavior);
    }

    public Door() {
    }

    @Override
    public void decoratorHouse() {
        super.decoratorHouse();
        System.out.println("3>>>>>>>>>>>>>>>>>>>>>安装门");
    }
}

5.启动类

public class Test {
    public static void main(String[] args) {
        RoughHome roughHome = new RoughHome();
        Floor floor = new Floor(roughHome);
        Door door =   new Door(floor);
        door.decoratorHouse();
    }
}

6.运行结果


图片.png

相关文章

网友评论

      本文标题:装饰模式

      本文链接:https://www.haomeiwen.com/subject/wectdltx.html