
- 設計模式教程
- 設計模式 - 首頁
- 設計模式 - 概述
- 設計模式 - 工廠模式
- 抽象工廠模式
- 設計模式 - 單例模式
- 設計模式 - 建造者模式
- 設計模式 - 原型模式
- 設計模式 - 介面卡模式
- 設計模式 - 橋接模式
- 設計模式 - 過濾器模式
- 設計模式 - 組合模式
- 設計模式 - 裝飾器模式
- 設計模式 - 外觀模式
- 設計模式 - 享元模式
- 設計模式 - 代理模式
- 責任鏈模式
- 設計模式 - 命令模式
- 設計模式 - 直譯器模式
- 設計模式 - 迭代器模式
- 設計模式 - 中介者模式
- 設計模式 - 備忘錄模式
- 設計模式 - 觀察者模式
- 設計模式 - 狀態模式
- 設計模式 - 空物件模式
- 設計模式 - 策略模式
- 設計模式 - 模板模式
- 設計模式 - 訪問者模式
- 設計模式 - MVC模式
- 業務代表模式
- 組合實體模式
- 資料訪問物件模式
- 前端控制器模式
- 攔截過濾器模式
- 服務定位器模式
- 傳輸物件模式
- 設計模式資源
- 設計模式 - 問答
- 設計模式 - 快速指南
- 設計模式 - 有用資源
- 設計模式 - 討論
設計模式 - 代理模式
在代理模式中,一個類代表另一個類的功能。這種設計模式屬於結構型模式。
在代理模式中,我們建立一個包含原始物件的代理物件,以將其功能介面到外部。
實現
我們將建立一個Image介面和實現Image介面的具體類。ProxyImage是一個代理類,用於減少RealImage物件載入的記憶體佔用。
ProxyPatternDemo,我們的演示類,將使用ProxyImage來獲取Image物件以根據需要載入和顯示。

步驟1
建立一個介面。
Image.java
public interface Image { void display(); }
步驟2
建立實現相同介面的具體類。
RealImage.java
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.java
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(); } }
步驟3
根據需要使用ProxyImage獲取RealImage類的物件。
ProxyPatternDemo.java
public class ProxyPatternDemo { public static void main(String[] args) { Image image = new ProxyImage("test_10mb.jpg"); //image will be loaded from disk image.display(); System.out.println(""); //image will not be loaded from disk image.display(); } }
步驟4
驗證輸出。
Loading test_10mb.jpg Displaying test_10mb.jpg Displaying test_10mb.jpg
廣告