设计模式—代理模式

介绍

代码

接口

创建接口 Image

public interface Image {
    void display();
}

实体类

创建实体类 RealImage

public class RealImage implements Image {
    private String fileName;

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

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

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

代理类

创建代理类 ProxyImage,将实体类作为属性

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

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

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

测试

public class ProxyTest {

    @Test
    void test() {
        Image image = new ProxyImage("test_10mb.jpg");

        // 图像将从磁盘加载
        image.display();
        System.out.println("------------");
        // 图像不需要从磁盘加载
        image.display();
    }
}
posted @ 2023-12-20 14:00  Frodo1124  阅读(14)  评论(0编辑  收藏  举报