月黑风高的午夜,一个神秘的顾客走进了"Midnight Gems",一个知名的珠宝店。店主,一个老练的珠宝工匠,拿出了一串普通的珠宝项链。顾客表示,他需要在这串项链上添加一些特别的饰品来使它更独特。
店主回忆起了装饰器模式——不改变原始对象,但可以添加新的功能。他决定用这种方法来装饰这串项链。
interface Jewelry {
String display();
}
class Necklace implements Jewelry {
@Override
public String display() {
return "Necklace";
}
}
abstract class JewelryDecorator implements Jewelry {
protected Jewelry decoratedJewelry;
public JewelryDecorator(Jewelry decoratedJewelry) {
this.decoratedJewelry = decoratedJewelry;
}
public String display() {
return decoratedJewelry.display();
}
}
class DiamondDecorator extends JewelryDecorator {
public DiamondDecorator(Jewelry decoratedJewelry) {
super(decoratedJewelry);
}
@Override
public String display() {
return super.display() + " with Diamonds";
}
}
class RubyDecorator extends JewelryDecorator {
public RubyDecorator(Jewelry decoratedJewelry) {
super(decoratedJewelry);
}
@Override
public String display() {
return super.display() + " with Rubies";
}
}
神秘顾客要求先加上钻石,再加上红宝石。店主依次使用了装饰器模式,得到了一个钻石和红宝石饰品的项链。
public class JewelryShop {
public static void main(String[] args) {
Jewelry basicNecklace = new Necklace();
Jewelry diamondNecklace = new DiamondDecorator(basicNecklace);
Jewelry diamondRubyNecklace = new RubyDecorator(diamondNecklace);
System.out.println(diamondRubyNecklace.display());
// 输出: Necklace with Diamonds with Rubies
}
}
在神秘顾客的眼中,项链在每一步都变得更加绚烂夺目。他对店主说:“在这短短的时间内,你展现了一种令人惊叹的技术。这就像你给我的项链增加了功能,而没有改变它的本质。”
店主微笑着答道:“这就是装饰器模式的魅力,它让我们可以在不改变对象的前提下,为其添加新的行为。”
业务场景分析:
装饰器模式非常适用于那些需要动态扩展功能,但又不想使用继承的场景。例如,Java中的IO流就大量使用了装饰器模式,允许我们创建各种组合的输入/输出流。另外,在web开发中,可以使用装饰器模式来添加中间件或者动态增加功能,如安全检查、日志记录等。
代码示例:
考虑一个web应用,你希望为请求添加日志和安全检查功能。使用装饰器模式,你可以动态地为请求添加这些功能,而不是改变原始的请求处理类。
interface RequestHandler {
void handle();
}
class BasicRequest implements RequestHandler {
@Override
public void handle() {
System.out.println("Handling basic request.");
}
}
class LoggingDecorator extends JewelryDecorator {
public LoggingDecorator(RequestHandler handler) {
super(handler);
}
@Override
public void handle() {
System.out.println("Logging request...");
super.handle();
}
}
class SecurityDecorator extends JewelryDecorator {
public SecurityDecorator(RequestHandler handler) {
super(handler);
}
@Override
public void handle() {
System.out.println("Checking security...");
super.handle();
}
}
使用这些装饰器,你可以轻松地为请求处理程序添加日志记录和安全检查功能,而不需要修改原始的BasicRequest
类。