什么是代理模式?
代理模式,一般是为了对真正的对象进行访问限制,延时实例化等,举一个例子:
生活中,书籍厂家生产书并且出售书,但是,如果你想买书的话,一定要到书籍厂家买吗?不是的,我们可以通过大大小小书店购买。
在这里,书籍厂家就是RealObject,它有一个方法sell();
书店就是代理对象ProxyObject,它也有一个方法sell(),这个方法通过调用realObject的sell()来实现出售书。
下面这个图可以方便我们理解:
如何实现代理模式?
根据上面的讲解,我们来实现一个代理模式:
定义一个Book类:
public class Book implements Parcelable{
private String name;
private int price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public Book(){
}
protected Book(Parcel in) {
name = in.readString();
price = in.readInt();
}
public static final Creator<Book> CREATOR = new Creator<Book>() {
@Override
public Book createFromParcel(Parcel in) {
return new Book(in);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(price);
}
public void readFromParcel(Parcel dest){
name = dest.readString();
price = dest.readInt();
}
@Override
public String toString() {
StringBuffer string = new StringBuffer();
string.append("name:" + name);
string.append("price:" + price);
return string.toString();
}
}
定义IBookFactory接口:
public interface IBookFactory {
Book sell();
}
定义BookFactory类:
public class BookFactory implements IBookFactory{
private List<Book> books = new ArrayList<>();
public BookFactory() {
for(int i=0;i<10;i++){
books.add(new Book("book" + i, i * 100));
}
}
@Override
public Book sell() {
if(books.size() > 0){
return books.remove(books.size()-1);
}
return null;
}
}
定义ProxyBookFactory类:
public class ProxyBookFactory implements IBookFactory {
private BookFactory bookFactory;
public ProxyBookFactory() {
bookFactory = new BookFactory();
}
@Override
public Book sell() {
return bookFactory.sell();
}
}
定义BookCustomer类:
public class BookCustomer {
private ProxyBookFactory proxyBookFactory;
public void setProxyObject(ProxyBookFactory proxyObject) {
this.proxyBookFactory = proxyObject;
}
public ProxyBookFactory getProxyObject() {
return proxyBookFactory;
}
public Book buyBook(){
return proxyBookFactory.sell();
}
}
定义调用函数:
public class Main {
public static void main(String[] args){
BookCustomer bookCustomer = new BookCustomer();
ProxyBookFactory proxyBookFactory = new ProxyBookFactory();
bookCustomer.setProxyObject(proxyBookFactory);
Book book = bookCustomer.buyBook();
System.out.println(book == null ? "null" : book.toString());
}
}
参考了:http://blog.csdn.net/hguisu/article/details/7542143
参考了:http://www.cnblogs.com/java-my-life/archive/2012/04/23/2466712.html