zoukankan      html  css  js  c++  java
  • [Design Pattern] Proxy Pattern 简单案例

    Proxy Pattern, 即代理模式,用一个类代表另一个类的功能,用于隐藏、解耦真正提供功能的类,属于结构类的设计模式。

    下面是 代理模式的一个简单案例。

    Image 定义接口,RealImage, ProxyImage 都实现该接口。RealImage 具有真正显示功能,ProxyImage 作为代表,暴露给客户端使用。

    代码实现:

    public interface Image {
        
        public void display();
    }

    RealImage 的实现,提供真正的功能

    public class RealImage implements Image {
    
        private String fileName;
        
        public RealImage(String fileName){
            this.fileName = fileName;
        }
        
        @Override
        public void display() {
            this.loadFromDisk();
            System.out.println("display - " + this.fileName);
        }
        
        public void loadFromDisk(){
            System.out.println("loading [" + this.fileName + "] from disk");
        }
    }

    ProxyImage ,代表 RealImage 提供对外功能

    public class ProxyImage implements Image {
    
        private String fileName;
        private RealImage realImage;
        
        public ProxyImage(String fileName){
            this.fileName = fileName;
            this.realImage = new RealImage(fileName);
        }
        
        @Override
        public void display() {
            realImage.display();
            System.out.println("proxyImage display " + fileName);
        }
    }

    演示代理模式,客户端调用代理层,无需了解具体提供功能的底层实现

    public class ProxyPatternDemo {
    
        public static void main(){
            ProxyImage proxyImage = new ProxyImage("aaa.txt");
            proxyImage.display();
        }
    }

    参考资料

    Design Patterns - Proxy Pattern, TutorialsPoint

  • 相关阅读:
    精妙SQL语句介绍
    ASP判断文件地址是否有效
    将源代码清空,这样别人就看不到源码了
    部署
    sublime
    vscode
    android node
    mac开启热点
    微信
    常见问题
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5515325.html
Copyright © 2011-2022 走看看