裝飾器模式用于動(dòng)態(tài)地為對(duì)象添加新功能,其核心在于通過組合而非繼承實(shí)現(xiàn)靈活擴(kuò)展。當(dāng)你需要以不同方式組合功能(如加密、壓縮消息)時(shí),避免因子類爆炸導(dǎo)致代碼混亂,裝飾器模式通過逐層包裝原始對(duì)象實(shí)現(xiàn)功能疊加,同時(shí)保持統(tǒng)一接口。具體步驟為:1. 定義公共接口或基類(如IMessage);2. 創(chuàng)建基本組件(如TextMessage);3. 構(gòu)建抽象裝飾器類,持有組件引用并實(shí)現(xiàn)相同接口;4. 實(shí)現(xiàn)具體裝飾器(如EncryptedMessageDecorator、CompressedMessageDecorator),在調(diào)用組件方法前后添加行為;5. 通過嵌套包裝組合多個(gè)裝飾器,實(shí)現(xiàn)功能疊加。例如在Web請(qǐng)求處理中,可依次應(yīng)用身份驗(yàn)證和日志記錄裝飾器,使每個(gè)裝飾器專注于單一職責(zé),增強(qiáng)代碼可維護(hù)性與復(fù)用性。
The Decorator pattern is a way to add new features or behaviors to an object dynamically, without changing its class. It’s especially useful when you want to extend functionality in a flexible and reusable way—unlike static inheritance, which can get messy fast.
Why You’d Use the Decorator Pattern
Let’s say you have a basic component, like a text message, and you want to add things like encryption, compression, or logging on top of it. Instead of creating separate subclasses for each possible combination (like EncryptedMessage, CompressedMessage, EncryptedAndCompressedMessage, etc.), the Decorator pattern wraps the original object with one or more decorators that add behavior as needed.
This keeps your code clean and makes it easier to mix and match features without rewriting a ton of classes.
For example:
- You start with a plain
TextMessage
. - Then wrap it with an
EncryptedMessageDecorator
. - Then maybe wrap that with a
CompressedMessageDecorator
.
Each layer adds functionality but still acts like a regular message object.
How It Works in Practice
At its core, the Decorator pattern relies on having a common interface or base class that both the main component and all decorators implement or extend. This allows decorators to freely wrap and enhance components without breaking compatibility.
Here’s a rough breakdown:
-
Component: The base interface or class (e.g.,
IMessage
). -
Concrete Component: The basic implementation (e.g.,
TextMessage
). - Decorator: An abstract class or base decorator that also implements the same interface and holds a reference to a component.
-
Concrete Decorators: Specific enhancements (e.g.,
EncryptedMessageDecorator
,CompressedMessageDecorator
).
Each concrete decorator calls the component's method first (like send()
) and then adds extra behavior before or after.
Real-World Example: Logging + Authentication
Imagine a web request handler. You might have:
- A basic
RequestHandler
that responds to HTTP requests. - A
LoggingDecorator
that logs the request before passing it along. - An
AuthDecorator
that checks if the user is logged in before proceeding.
You could stack them like this:
$handler = new AuthDecorator(new LoggingDecorator(new HomeController()));
Now, every time handle()
is called, it first checks authentication, then logs the request, then runs the actual controller logic.
This kind of chaining is powerful and keeps each piece focused on just one job.
That’s basically how the Decorator pattern works. It’s not hard once you see the structure, but it can be easy to miss the point if you're used to solving everything with inheritance.
The above is the detailed content of What is the Decorator pattern?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

The SpringMVC framework uses the following design patterns: 1. Singleton mode: manages the Spring container; 2. Facade mode: coordinates controller, view and model interaction; 3. Strategy mode: selects a request handler based on the request; 4. Observer mode: publishes and listen for application events. These design patterns enhance the functionality and flexibility of SpringMVC, allowing developers to create efficient and maintainable applications.

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.
