代理模式 -- 设计模式
在代理模式(Proxy Pattern)中,一个类代表另一个类的功能。
思考: 这种代理模式是最简单的代理模式, 跟装饰器模式相类似, 但是在Java中还有JDK代理和子类代理的其他代理方式
package day0320.ProxyPattern; public class Demo{ public static void main(String[] args){ Image image = new ProxyImage("C:/users/jack/desktop/test.png"); image.display(); } } interface Image { void display(); } class RealImage implements Image{ private String path; @Override public void display(){ System.out.println("displaying image: " + this.path); } public void loadFromDisk(String path) { this.path = path; System.out.println("loading image from disk: " + path); } } class ProxyImage implements Image{ RealImage realImage; String filePath; public ProxyImage(String filePath){ this.realImage = new RealImage(); this.filePath = filePath; } public ProxyImage(RealImage realImage, String filePath){ this.realImage = realImage; this.filePath = filePath; } @Override public void display(){ if (this.filePath == null) { throw new RuntimeException("Can't load this file: " + this.filePath); } else if (this.filePath.startsWith("C:")) { throw new RuntimeException("You have no privillage to access file in disk C:"); } realImage.loadFromDisk(filePath); realImage.display(); } }