UML图:
源码:Image接口
public interface Image {
void show();
}
ProxyImage类
public class ProxyImage implements Image {
Image img;
public ProxyImage(Image img) {
super();
this.img = img;
System.out.println("数据代理初始化完成……");
}
@Override
public void show() {
if (img==null) {
img=new RealImage();
}
img.show();
}
}
RealImage类
public class RealImage implements Image {
public RealImage() {
System.out.println("真是数据初始化完成");
}
@Override
public void show() {
System.out.println("加载图片中……");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("成功载入数据!");
}
}
ImageFactory类
public class ImageFactory {
public static Image createImage(char ch){
Image image=null;
switch (ch) {
case 'P':
image=new ProxyImage(null);
break;
case 'R':
image=new RealImage();
break;
}
return image;
}
}
客户端:
public class Client {
public static void main(String[] args) {
Image image = null;
//通过注释来改变用不用代理
// System.out.println("使用代理");
// image = new ImageFactory().createImage('R');
System.out.println("不使用代理");
image = new ImageFactory().createImage('P');
image.show();
}
}