打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java之装饰模式(Decorator Pattern)

1. 概念

动态将职责附加到对象上,若要扩展功能,装饰者提供了比继承更具弹性的代替方案。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。[由于继承的静态特质使其缺乏灵活性;且随着子类的增多、组合,会导致更多子类的膨胀。类应设计的对扩展开放,对修改关闭。装饰的意思:就是包装一下。把另的对象包装一下。]

2. UML图

3.代码

/************业务接口 Component************/
  public interface Component
{
void operation();
}

 

/************业务接口 Component************/
public class ConcreteComponent implements Component {
public void operation() {
//
}
}

 

/************装饰 Decorator************/
public class Decorator implements Component
{
private Component component;

public Decorator(Component component)
{
this.component = component;
}

public void operation()
{
component.operation();
}
}

 


/************具体Decorator************/
    public class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component) {
super(component);
}

public void operation()
{
super.operation();

addBehavior();
}

private void addBehavior()
{
System.out.println("addBehavior");
}
}

 

/************运行示例************/
        ConcreteDecorator concreteDecorator=new ConcreteDecorator(new ConcreteComponent());
        concreteDecorator.operation();

4.应用场景

1)需要扩展一个类的功能,或给一个类增加附加责任。

2)需要动态地给一个对象增加功能,这些功能可以再动态地撤销。

3)需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
设计模式笔记 – Decorator 装饰模式 (Design Pattern) 及其在J...
扩展系统功能——装饰模式(二)
详解JAVA面向对象的设计模式 (七)、装饰模式
装饰模式(Decorator Pattern)
大话设计模式笔记(四)の装饰模式
设计模式(1)装饰模式总结
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服