Java设计模式-装饰者模式

模拟穿衣服场景

我们来看下面一个具体的案例:每个人一天起床之后都要穿衣服(来装饰自己),这是必不可少的,这样问题就来了,穿什么?按照什么顺序穿?
如何用程序方便的模拟这个场景的,代码如下:

/**
* 程序模拟一个人穿衣服的过程
* @author: qhyuan1992
*/
// 抽象接口,用来规范将要被附加一些操作的对象
interface People{
    public void wear();
}

// 具体的对象,该对象将被附加一些额外的操作
class Jane implements People{
    public void wear() {
        System.out.println("今天该穿什么呢?");
    }
}

// 装饰者类,持有一个将要被装饰的接口对象的实例
class Decorator implements People{

    private People people;

    public Decorator(People people) {
        this.people = people;
    }
    public void wear() {
        people.wear();
    }
}

// 具体的装饰者类,负责给增加附加的操作:穿衬衫
class DecoratorShirt extends Decorator{

    public DecoratorShirt(People people) {
        super(people);
    }

    public void wear() {
        super.wear();
        System.out.println("穿个衬衫");
    }
}

// 具体的装饰者类,负责给增加附加的操作:穿西服
class DecoratorSuit extends Decorator{

    public DecoratorSuit(People people) {
        super(people);
    }

    public void wear() {
        super.wear();
        System.out.println("穿个西服");
    }
}

// 具体的装饰者类,负责给增加附加的操作:穿T-Shirt
class DecoratorTShirt extends Decorator{

    public DecoratorTShirt(People people) {
        super(people);
    }

    public void wear() {
        super.wear();
        System.out.println("穿个T-Shirt");
    }
}

// 具体的装饰者类,负责给增加附加的操作:穿裤子
class DecoratorPants extends Decorator{

    public DecoratorPants(People people) {
        super(people);
    }

    public void wear() {
        super.wear();
        System.out.println("穿裤子");
    }
}

// 具体的装饰者类,负责给增加附加的操作:穿鞋子
class DecoratorShoes extends Decorator{

    public DecoratorShoes(People people) {
        super(people);
    }

    public void wear() {
        super.wear();
        System.out.println("鞋子");
    }
}

public class DecoratorTest {
   

    public static void main(String[] args) {
        People p1 = new Decorator
  • 11
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值