装扮模式

本文通过一个具体的Java实现案例,介绍了装饰者模式的基本概念及其应用。案例中定义了一个Person类作为被装饰的对象,并创建了多个装饰类如TShirt、BigTrouser等来为Person对象增加不同的装扮。

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

照例大话设计模式的例子,用java模仿了一遍,代码如下:
1.person类

public class Person {
    public Person() {
    }// 构造函数

    private String name;

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

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

}

2.装饰类

public class Decorator extends Person {
    protected Person component;
    //打扮
    public void decorate(Person component){
        this.component=component;
    }
    public void show(){
        if(component!=null){
            component.show();
        }
    }
}

3.具体服饰类

class TShirt extends Decorator{
    public void show(){
        System.out.print("大T恤 ");
        super.show();
    }
}
class BigTrouser extends Decorator{
    public void show(){
        System.out.print("垮裤 ");
        super.show();
    }
}
class Sneakers extends Decorator{
    public void show(){
        System.out.print("破球鞋 ");
        super.show();
    }
}
class Suit extends Decorator{
    public void show(){
        System.out.print("西装 ");
        super.show();
    }
}
class Tie extends Decorator{
    public void show(){
        System.out.print("领带 ");
        super.show();
    }
}
class LeatherShoes extends Decorator{
    public void show(){
        System.out.print("皮鞋 ");
        super.show();
    }
}

4.客户端

public class Client {

    public static void main(String[] args) {
        Person xc = new Person("小菜");
        System.out.println("第一种装扮:");
        TShirt dtx = new TShirt();
        BigTrouser kk = new BigTrouser();
        Sneakers pqx = new Sneakers();

        dtx.decorate(xc);
        kk.decorate(dtx);
        pqx.decorate(kk);
        pqx.show();

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值