java 装饰模式(大话设计模式)
发布日期:2021-05-19 21:35:51 浏览次数:18 分类:精选文章

本文共 2175 字,大约阅读时间需要 7 分钟。

装饰模式(Decorator Pattern)是一种在软件设计中常用的设计模式,其核心思想是通过动态地为一个对象添加一些额外的职责,从而灵活地增加功能。相比于生成子类,这种模式更为灵活且柔性。

装饰模式的实现方式是通过一个包装类(Decorator),它继承自一个抽象类(Component),并将要装饰的对象作为这个组件的一部分。具体来说,Decorator类不仅继承Component类,还在其中嵌入一个Component对象。Decorator类中定义了一个set方法,用来将需要装饰的对象赋值给内部的Component对象。这样,当需要执行操作时,Decorator类的operation方法会先调用内部Component对象的operation方法,从而实现了职责的动态添加。

在装饰模式的实现中,Decorator抽象类的操作方法(operation())会调用内部组件的操作方法。这样设计的好处是,每个具体的Decorator类可以在自己的operation方法中首先调用父类的方法,然后执行自身的特定行为。例如,一个ConcreteDecoratorA类在其operation方法中,会先执行父类的operation,再添加一个额外的行为。

通过这种方式,装饰模式实现了对原有功能的动态扩展,便于在运行时根据需求选择性地添加功能包装对象。

以下是一个实际应用场景的示例:

装饰模式案例:穿衣服

在这个案例中,我们使用装饰模式来模拟衣着装扮的逻辑。Person类代表一个人物,Finery类则是衣饰的基类,负责将这些衣饰装饰到人物身上。

  • Person类

    public class Person {
    private String name;
    public Person(String name) {
    this.name = name;
    }
    public void show() {
    System.out.println("装扮的" + name);
    }
    }
  • Finery类

    public class Finery extends Person {
    protected Person component;
    public void decorate(Person component) {
    this.component = component;
    }
    @Override
    public void show() {
    if (component != null) {
    component.show();
    }
    }
    }
  • 具体的装饰类

    • TShirts,装饰对象的上衣部分,带有“大T恤”的描述。
    • BigTrouser,装饰对象的裤子部分,带有“大裤头”的描述。
    • Sneakers,装饰对象的鞋子部分,带有“破球鞋”的描述。
    • Suit,装饰对象的西装部分。
    • Tie,装饰对象的领带部分。
    • LeatherShoes,装饰对象的皮鞋部分。
  • 客户端调用示例

    public class Attire {
    public static void main(String[] args) {
    Person p0 = new Person("Kobe");
    System.out.println("第一种装扮:");
    TShirts tShirts = new TShirts();
    BigTrouser bigTrouser = new BigTrouser();
    Sneakers sneakers = new Sneakers();
    tShirts.decorate(p0);
    bigTrouser.decorate(tShirts);
    sneakers.decorate(bigTrouser);
    sneakers.show();
    Person p1 = new Person("Allen");
    System.out.println("第二种装扮:");
    Suit suit = new Suit();
    Tie tie = new Tie();
    LeatherShoes leatherShoes = new LeatherShoes();
    leatherShoes.decorate(p1);
    tie.decorate(leatherShoes);
    suit.decorate(tie);
    suit.show();
    }
    }
  • 在这个案例中,装饰模式通过层层包装的方式,为人物的不同部位添加了不同的衣饰效果,体现了动态职责添加的特点。每个具体的Decorator类都通过继承自Finery类,并在自己的方法中对外部组件进行操作,从而实现了对服饰功能的灵活扩展。

    上一篇:java 工厂模式(大话设计模式)
    下一篇:java 策略模式(大话设计模式)

    发表评论

    最新留言

    留言是一种美德,欢迎回访!
    [***.207.175.100]2025年04月19日 03时05分32秒