《大话设计模式》Java代码示例(三)之装饰模式

本文深入探讨了装饰模式在软件设计中的应用,通过实例演示了如何动态地给对象添加职责,展示了装饰模式相较于生成子类的灵活性。通过具体的Java代码,解释了装饰者模式的基本原理和实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

 

package decorator;

/**
 * 装饰模式(Decorator)
 * Person类
 */
public class Person {

    private String name;

    public Person() {}

    public Person(String name) {
        this.name = name;
    }

    public void show() {
        System.out.println("装扮的" + name);
    }

}
package decorator;

/**
 * 装饰模式(Decorator)
 * 服饰类
 */
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();
        }
    }

}

class TShirts extends Finery {

    public void show() {
        System.out.print("大T恤  ");
        super.show();
    }

}

class BigTrouser extends Finery {

    public void show() {
        System.out.print("大裤头  ");
        super.show();
    }

}

class Sneakers extends Finery {

    public void show() {
        System.out.print("破球鞋  ");
        super.show();
    }

}

class Suit extends Finery {

    public void show() {
        System.out.print("西装  ");
        super.show();
    }

}

class Tie extends Finery {

    public void show() {
        System.out.print("领带  ");
        super.show();
    }

}

class LeatherShoes extends Finery {

    public void show() {
        System.out.print("皮鞋  ");
        super.show();
    }

}
package decorator;

/**
 * 装饰模式(Decorator)
 * 客户端main方法
 */
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();

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值