解决的问题
开发一个电子书app,可以这样设计:
不使用代理模式.png
每个电子书实例化后,都要占用一些计算机资源(CPU、内存等),那么当电子书多了后,就会有性能问题。
这样情况,可以使用Proxy Pattern进行优化:
使用代理模式.png
图书馆一开始,只是持有电子书的代理,电子书并没有真正的实例化。等到要打开电子书时,才会真正地实例化电子书。通过这样的方式解决的性能问题。
代码
EBook
:
package com.cong.designpattern.proxy;
public interface EBook {
public String getName();
public void open();
}
RealEBook
:
package com.cong.designpattern.proxy;
public class RealEBook implements EBook{
private String name;
public RealEBook(String name) {
this.name = name;
this.load();
}
private void load() {
System.out.println("Load ebook " + this.name);
}
@Override
public String getName() {
return this.name;
}
@Override
public void open() {
System.out.println("Open " + this.name);
}
}
EBookProxy
:
package com.cong.designpattern.proxy;
public class EBookProxy implements EBook{
private RealEBook realEBook;
private String name;
public EBookProxy(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
public void open() {
if (this.realEBook == null) this.realEBook = new RealEBook(this.name);
this.realEBook.open();
}
}
Library
:
package com.cong.designpattern.proxy;
import java.util.HashMap;
import java.util.Map;
public class Library {
private Map<String, EBook> eBookMap = new HashMap<>();
public void add(EBook eBook) {
this.eBookMap.put(eBook.getName(), eBook);
}
public EBook getEBook(String name) {
return this.eBookMap.get(name);
}
}
Test code:
Library library = new Library();
String[] names = {"a", "b", "c", "d", "e"};
for (String name:names) library.add(new EBookProxy(name));
EBook eBook = library.getEBook("a");
eBook.open();
网友评论