在以下示例中,来自Wiki书https://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Proxy
我不知道这比仅创建真实对象并使用其中的显示图像更快或更有效。因为代理还是在displayImage方法中创建了真实的对象?
//on System B
class ProxyImage implements Image {
private RealImage image = null;
private String filename = null;
/**
* Constructor
* @param FILENAME
*/
public ProxyImage(final String FILENAME) {
filename = FILENAME;
}
/**
* Displays the image
*/
public void displayImage() {
if (image == null) {
image = new RealImage(filename);
}
image.displayImage();
}
}
如果不使用代理,代理模式肯定会节省内存,因为它需要实例化两个对象(代理和实数),而不是仅实例化一个(实数)?
通过您发布的链接(重点是我的):
代理类
ProxyImage
在真实图像类本身之外的其他系统上运行,并且可以在该系统上表示真实图像RealImage
。可从磁盘访问映像信息。使用代理模式,的代码ProxyImage
避免了多次加载图像,从而以节省内存的方式从其他系统访问该图像。
简而言之:它不节省内存,它可以加快应用程序的速度,因为您不需要每次都访问磁盘来读取真实图像。
这在代码的这一部分中得到了证明:
public void displayImage() {
//if image is not loaded into memory
if (image == null) {
//then load it, go to disk only once
image = new RealImage(filename);
}
//now it is in memory, display the real image
image.displayImage();
}
为了更好地理解此问题,让我们更改类和接口的定义:
public interface Image {
String getName();
byte[] getData();
}
现在,RealImage
该类将始终在磁盘中寻找数据,以防文件不存在(文件被删除或重命名):
public class RealImage implements Image {
//implements all the operations going to disk...
private String fileName;
public RealImage(String fileName) {
this.fileName = fileName;
}
@Override
public String getName() {
String name = "";
//fancy operations to seek for the file in disk (in case it has been deleted)
//read the data from file in disk
//get the name
name = ...;
return name;
}
@Override
public byte[] getData() {
byte[] data;
//again, fancy operations to seek for the file in disk (in case it has been deleted)
//read the data from file in disk
//get the image data for displaying purposes
data = ...;
return data;
}
}
现在,我们的商品ProxyImage
将充当代理,RealImage
通过将数据保存到内存中来节省每次昂贵的磁盘任务:
public class ProxyImage implements Image {
private String fileName;
private RealImage realImage;
private byte[] data;
private String name;
//implements all the operations going to disk...
public RealImage(String fileName) {
this.fileName = fileName;
}
@Override
public String getName() {
//in case we don't have the name of the image
if (this.name == null) {
//use a RealImage to retrieve the image name
//we will create the instance of realImage only if needed
if (realImage == null) {
realImage = new RealImage(fileName);
}
//getting the image from the real image is highly costly
//so we will do this only once
this.name = realImage.getName();
}
return this.name;
}
@Override
public byte[] getData() {
//similar behavior for the data of the image
if (this.data == null) {
if (realImage == null) {
realImage = new RealImage(fileName);
}
//highly costly operation
this.data = realImage.getData();
}
return this.data;
}
}
因此反映了为我们的代理使用代理的好处RealImage
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句