设计模式之装饰器模式

设计模式之装饰器模式

如果现在有个需求,让你定义一个男人戴帽子。你会先定义一个人的接口,然后男人实现接口,并加入戴帽子的方法。但是如果再让你加上穿衣服的功能,在不改变原有代码的基础上,你会写一个继承类实现穿衣服的功能。但是需求又增多了呢,那么就造成继承类太多,这个时候就可以用装饰器模式。
先定义person接口

public interface Person {
    void show();
}

在定义男人类实现接口

public class Man implements Person {
    @Override
    public void show() {
        System.out.println("我是男人");
    }
}

定义抽象装饰器类

public abstract class PersonDecorator implements Person {
    protected Person DecoratorPerson;

    public PersonDecorator(Person DecoratorPerson) {
        this.DecoratorPerson = DecoratorPerson;
    }
    
    @Override
    public void show() {
        DecoratorPerson.show();
    }
}

具体帽子装饰器类

public class CapPersonDecorator extends PersonDecorator {
    public CapPersonDecorator(Person DecoratorPerson) {
        super(DecoratorPerson);
    }

    @Override
    public void show() {
        super.show();
        setTake(DecoratorPerson);
    }
    private void setTake(Person DecoratorPerson){
        System.out.println("戴帽子");
    }
}

具体衣服装饰器类

public class ClosePersonDecorator extends PersonDecorator {
    public ClosePersonDecorator(Person DecoratorPerson) {
        super(DecoratorPerson);
    }

    @Override
    public void show() {
        DecoratorPerson.show();
        setTake(DecoratorPerson);
    }
    private void setTake(Person DecoratorPerson){
        System.out.println("穿衣服");
    }
}

客户端测试类

public class test {
    public static void main(String[] args) {
//        Person person1=new CapPersonDecorator(
    	  new ClosePersonDecorator(new Man()));
//
//        person1.show();
//        System.out.println();
            //也可以写成下面的写法

        Person person=new Man();
        Person person2=new ClosePersonDecorator(person);

        Person person3=new CapPersonDecorator(person2);
        person3.show();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值