介绍
代码
接口
创建接口 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();
}
}
标签:String,Image,代理,模式,display,RealImage,fileName,设计模式,public
From: https://www.cnblogs.com/shixuanliu/p/17916350.html