介面的應用——代理設計模式(Proxy)(課堂筆記)
阿新 • • 發佈:2019-02-14
代理設計模式和工廠設計模式相反,工廠設計模式是Factory類實現多個介面,而代理設計模式是多個子類實現一個介面,從而可以讓代理主題類來完成真實主題的部分操作。下面是一個簡單是例子:interface Subject{
public void make();
}
class RealSubject implements Subject{
public void make(){
System.out.println("真實主題要做的事!");
}
}class ProxySubject implements Subject{
Subject subject;
public ProxySubject(Subject subject) {
this.subject = subject;
}
public void print(){
System.out.println("為事前做準備!");
}
public void destroy(){
System.out.println("為真實主題操作後的收尾");
}
public void make(){
print();
subject.make();
destroy();
}
}
public class Gpp { public static void main(String[] args) {
Subject sub =new ProxySubject(new RealSubject());
sub.make(); }}
public void make();
}
class RealSubject implements Subject{
public void make(){
System.out.println("真實主題要做的事!");
}
}class ProxySubject implements Subject{
Subject subject;
public ProxySubject(Subject subject) {
this.subject = subject;
}
public void print(){
System.out.println("為事前做準備!");
}
public void destroy(){
System.out.println("為真實主題操作後的收尾");
}
public void make(){
print();
subject.make();
destroy();
}
}
public class Gpp { public static void main(String[] args) {
Subject sub =new ProxySubject(new RealSubject());
sub.make(); }}