代理模式
在代理模式中,一个类代表另一个类的功能
image
public interface Image {
void display();
}
RealImage
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
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();
}
}
ProxyPatternDemo
public class ProxyPatternDemo {
public static void main(String[] args) {
Image image = new ProxyImage("Hello");
image.display();
System.out.println("");
image.display();
}
}
看初始化的时候找了real得到代理,之后都是代理类完成任务了。。。
Loading hello
Displaying hello
Displaying hello