代理模式
来自维基百科,自由的百科全书
来自维基百科,自由的百科全书
代理模式(英語:Proxy Pattern)是程式設計中的一種設計模式。
所謂的代理者是指一個類別可以作為其它東西的介面。代理者可以作任何東西的介面:網絡連接、記憶體中的大物件、檔案或其它昂貴或無法複製的資源。
著名的代理模式例子為參照計數(英語:reference counting)指標物件。
當一個複雜物件的多份副本須存在時,代理模式可以結合享元模式以減少記憶體用量。典型作法是建立一個複雜物件及多個代理者,每個代理者會參照到原本的複雜物件。而作用在代理者的運算會轉送到原本物件。一旦所有的代理者都不存在時,複雜物件會被移除。
以下Java範例解釋"虛擬代理"模式。ProxyImage
類別用來存取遠端方法。
import java.util.*;
interface Image {
public void displayImage();
}
//on System A
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadImageFromDisk();
}
private void loadImageFromDisk() {
System.out.println("Loading " + filename);
}
public void displayImage() {
System.out.println("Displaying " + filename);
}
}
//on System B
class ProxyImage implements Image {
private String filename;
private Image image;
public ProxyImage(String filename) {
this.filename = filename;
}
public void displayImage() {
if(image == null)
image = new RealImage(filename);
image.displayImage();
}
}
class ProxyExample {
public static void main(String[] args) {
Image image1 = new ProxyImage("HiRes_10MB_Photo1");
Image image2 = new ProxyImage("HiRes_10MB_Photo2");
image1.displayImage(); // loading necessary
image2.displayImage(); // loading necessary
}
}
程式的輸出為:
Loading HiRes_10MB_Photo1 Displaying HiRes_10MB_Photo1 Loading HiRes_10MB_Photo2 Displaying HiRes_10MB_Photo2
using System;
namespace Proxy
{
class Program
{
interface IImage
{
void Display();
}
class RealImage : IImage
{
public RealImage(string fileName)
{
FileName = fileName;
LoadFromFile();
}
private void LoadFromFile()
{
Console.WriteLine("Loading " + FileName);
}
public String FileName { get; private set; }
public void Display()
{
Console.WriteLine("Displaying " + FileName);
}
}
class ProxyImage : IImage
{
public ProxyImage(string fileName)
{
FileName = fileName;
}
public String FileName { get; private set; }
private IImage image;
public void Display()
{
if (image == null)
image = new RealImage(FileName);
image.Display();
}
}
static void Main(string[] args)
{
IImage image = new ProxyImage("HiRes_Image");
for (int i = 0; i < 10; i++)
image.Display();
}
}
}
程式的輸出為:
Loading HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image Displaying HiRes_Image
Seamless Wikipedia browsing. On steroids.
Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.
Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.