设计模式-装饰器模式

装饰器模式

定义:不改变原类文件和继承关系的情况下,动态扩展一个对象的功能。他是通过创建一个包装对象。

使用场景:不想使用继承,但又要在原有基础上增加额外功能。如一部手机,给他增加一个手机壳,再增加一个保护膜。

结构:

  • 抽象构件(Component):定义一个抽象接口
  • 具体构件(ConcreteComponent):实现抽象构件
  • 抽象装饰(Decorator):继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能
  • 具体装饰(ConcreteDecorator):实现抽象装饰的相关方法,并给具体构件对象添加附加功能

给一个只有打电话功能的手机增加功能。

代码示例:

public interface IPhone {
    void call();
}
public class Xiaomi implements IPhone {
    @Override
    public void call() {
        System.out.println("我有打电话的功能");
    }
}
public class DecoratorPhone implements IPhone{

    private IPhone iPhone;

    public DecoratorPhone(IPhone iPhone) {
        this.iPhone = iPhone;
    }

    @Override
    public void call(){
        iPhone.call();
    }
}


public class MusicPhone extends DecoratorPhone {

    public MusicPhone(IPhone iPhone) {
        super(iPhone);
    }

    @Override
    public void call() {
        super.call();
        System.out.println("我有了播放音乐功能");
    }
}
public class PlayGamePhone extends DecoratorPhone {

    public PlayGamePhone(IPhone iPhone) {
        super(iPhone);
    }

    @Override
    public void call() {
        super.call();
        System.out.println("我有了打游戏功能");
    }
}

测试代码:

 public static void main(String[] args) throws InterruptedException, CloneNotSupportedException {
        IPhone iPhone=new Xiaomi();
        IPhone musicPhone=new MusicPhone(iPhone);
        IPhone playPhone=new PlayGamePhone(musicPhone);
        playPhone.call();

    }

返回目录

posted @ 2021-06-27 17:49  女友在高考  阅读(52)  评论(0编辑  收藏  举报