java设计模式---装饰模式

本文介绍装饰者模式的概念及其应用场景,通过示例代码展示了如何在不影响其他对象的情况下为单个对象动态添加职责,以及如何实现这些功能的具体步骤。

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

1.概念

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

2.适用性

1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。   

 2.处理那些可以撤消的职责。

 3.当不能采用生成子类的方法进行扩充时。

3.参与者

1.Component    

  定义一个对象接口,可以给这些对象动态地添加职责。  

  2.ConcreteComponent   

   定义一个对象,可以给这个对象添加一些职责。  

  3.Decorator     

 维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。

    4.ConcreteDecorator   

   向组件添加职责。

示例:

Component 

 //接口

public interface Person {

 

    void eat();

}

ConcreteComponent 

 //实现接口

public class Man implements Person {

 

public void eat() {

System.out.println("男人在吃");

}

}

 

Decorator 

 

public abstract class Decorator implements Person {

 

    protected Person person;

    

    public void setPerson(Person person) {

        this.person = person;

    }

    

    public void eat() {

        person.eat();

    }

}

ConcreteDectrator 

 

public class ManDecoratorA extends Decorator {

 

    public void eat() {

        super.eat();

        reEat();

        System.out.println("ManDecoratorA类");

    }

 

    public void reEat() {

        System.out.println("再吃一顿饭");

    }

}

public class ManDecoratorB extends Decorator {

    

    public void eat() {

        super.eat();

        System.out.println("===============");

        System.out.println("ManDecoratorB类");

    }

}

Test 

 

public class Test {

 

    public static void main(String[] args) {

        Man man = new Man();

        ManDecoratorA md1 = new ManDecoratorA();

        ManDecoratorB md2 = new ManDecoratorB();

        

        md1.setPerson(man);

        md2.setPerson(md1);

        md2.eat();

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值