Provide a surrogate or placeholder for another object to control access to it.
为其他对象提供一个代理以控制对这个对象的访问。
public interface IImage {
void DisplayImage();
}
public class RealImage : IImage {
private readonly string _fileName;
public RealImage(string fileName) {
this._fileName = fileName;
this.LoadImageFromFile();
}
private void LoadImageFromFile() {
Console.WriteLine("Load image from file {0}", this._fileName);
}
public void DisplayImage() {
Console.WriteLine("Displaying image {0}", this._fileName);
}
}
public class ProxyImage : IImage {
private RealImage _realImage;
private readonly string _fileName;
public ProxyImage(string fileName) {
this._fileName = fileName;
}
public void DisplayImage() {
if (this._realImage == null) {
this._realImage = new RealImage(this._fileName);
}
this._realImage.DisplayImage();
}
}
class Program {
static void Main(string[] args) {
IImage image1 = new ProxyImage("HiRes_10MB_Photo1");
IImage image2 = new ProxyImage("HiRes_10MB_Photo2");
image1.DisplayImage();
image1.DisplayImage();
image2.DisplayImage();
image2.DisplayImage();
Console.ReadKey();
}
}