DECORATOR (Object Structural)
Purpose
Allows for the dynamic wrapping of objects in order to modify
their existing responsibilities and behaviors.
Use When
1 Object responsibilities and behaviors should be dynamically
modifiable.
2 Concrete implementations should be decoupled from
responsibilities and behaviors.
3 Subclassing to achieve modification is impractical or impossible.
4 Specific functionality should not reside high in the object hierarchy.
5 A lot of little objects surrounding a concrete implementation is
acceptable.
Example
Many businesses set up their mail systems to take advantage of
decorators. When messages are sent from someone in the company
to an external address the mail server decorates the original
message with copyright and confidentiality information. As long
as the message remains internal the information is not attached.
This decoration allows the message itself to remain unchanged
until a runtime decision is made to wrap the message with
additional information.
- package javaPattern;
-
- interface Component{
- public void operation();
- }
- class ConcreteComponent implements Component{
- public void operation(){
- System.out.println("某具体操作方法");
- }
- }
- public abstract class Decorator implements Component{
-
- public abstract void operation();
- public abstract void addedBehavior();
- }
- class ConcreteDecorator extends Decorator{
-
- private String addedState;
- @Override
- public void operation() {
- System.out.println("具体装饰类的某具体方法");
-
- }
- @Override
- public void addedBehavior(){
- System.out.println("新增加的方法");
- }
- }
分享到:
相关推荐
装饰者模式是面向对象设计模式的一种,主要用于动态地给一个对象添加一些额外的职责,而不会改变该对象的类。这种模式允许我们独立于对象的类来扩展对象的功能,为对象提供新的行为,同时保持了代码的可读性和可维护...
装饰者模式是软件设计模式中的一种结构型模式,它...综上所述,装饰者模式在Java编程中是一种重要的设计模式,尤其适用于需要动态添加或删除对象功能的场景。通过以上示例和解释,我们可以更好地理解和应用装饰者模式。
Java设计模式是面向对象编程领域中的重要概念,它是一套被广泛接受并实践的解决软件设计问题的经验总结。设计模式并非具体的代码或库,而是一种在特定情境下为了解决常见问题而制定的通用解决方案的描述。它们描述了...
Java 经典设计模式讲解以及项目实战 设计模式简介:主要介绍各种设计模式的概念和运用场景等 设计模式综合运用:主要是笔者在实际工作中运用到的一些设计模式综合运用事例的提炼 Spring设计模式简介:主要是讲述...
《Java设计模式之禅》是一本深入浅出讲解设计模式的书籍,书中不仅包含23种经典设计模式的案例,还详细介绍了设计模式背后的思想和原则,适合初学者以及对设计模式有一定了解的程序员阅读。本书旨在帮助读者理解如何...