装饰器模式与代理模式之间有什么区别和联系?请通过代码示例说明两者的不同。

装饰器模式和代理模式都属于结构型设计模式,它们在某些情况下会让人感到混淆,但它们的核心思想和使用场景有所不同。以下是两者的区别和联系,并通过代码示例说明其不同之处。

1. 代理模式 代理模式的主要目的是控制对对象的访问,通常用于权限控制、延迟加载、远程调用等场景。代理类和被代理类实现相同的接口,代理类内部持有被代理类的实例,并在调用前后可以添加额外的逻辑。

示例代码:

interface Image {
    void display();
}

class RealImage implements Image {
    private String fileName;

    public RealImage(String fileName) {
        this.fileName = fileName;
        loadFromDisk();
    }

    private void loadFromDisk() {
        System.out.println("Loading " + fileName);
    }

    public void display() {
        System.out.println("Displaying " + fileName);
    }
}

class ProxyImage implements Image {
    private RealImage realImage;
    private String fileName;

    public ProxyImage(String fileName) {
        this.fileName = fileName;
    }

    public void display() {
        if (realImage == null) {
            realImage = new RealImage(fileName);
        }
        realImage.display();
    }
}

public class ProxyPatternDemo {
    public static void main(String[] args) {
        Image image = new ProxyImage("test.jpg");
        // 图像未被加载
        image.display(); // 第一次调用时加载并显示
        image.display(); // 直接显示,无需重新加载
    }
}

2. 装饰器模式 装饰器模式的主要目的是动态地为对象添加额外的功能,而无需修改其结构。装饰器类同样实现与被装饰对象相同的接口,但装饰器类通常会在调用被装饰对象的操作前后添加额外的行为。

示例代码:

interface Shape {
    void draw();
}

class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing Circle");
    }
}

class Rectangle implements Shape {
    public void draw() {
        System.out.println("Drawing Rectangle");
    }
}

abstract class ShapeDecorator implements Shape {
    protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }

    public void draw() {
        decoratedShape.draw();
    }
}

class RedShapeDecorator extends ShapeDecorator {
    public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }

    public void draw() {
        decoratedShape.draw();
        setRedBorder();
    }

    private void setRedBorder() {
        System.out.println("Border Color: Red");
    }
}

public class DecoratorPatternDemo {
    public static void main(String[] args) {
        Shape circle = new Circle();
        Shape redCircle = new RedShapeDecorator(new Circle());
        Shape redRectangle = new RedShapeDecorator(new Rectangle());

        System.out.println("Circle with normal border");
        circle.draw();

        System.out.println("Circle of red border");
        redCircle.draw();

        System.out.println("Rectangle of red border");
        redRectangle.draw();
    }
}

3. 区别和联系

  • 目的不同:代理模式主要用于控制访问,装饰器模式主要用于动态扩展功能。
  • 侧重点不同:代理模式更强调对对象的间接访问,而装饰器模式更强调对功能的增强。
  • 相似点:两者都通过持有目标对象的实例来实现间接调用,且都遵循开闭原则。

通过上述示例可以看出,代理模式在第一次调用时才加载真实对象(RealImage),而装饰器模式在调用目标对象的同时动态添加了额外功能(如红色边框)。