Java之Proxy设计模式
Proxy设计的核心就是:只关心操作的核心,其余的操作交给另一个代理。
package Demo_1_24_Proxy; public interface IEat { // 吃的标准接口 public void get(); }
package Demo_1_24_Proxy; public class EatReal implements IEat{ //吃饭的地方 @Override public void get() { System.out.println("正在xx饭店吃饭!!"); } }
package Demo_1_24_Proxy; public class EatProxy implements IEat{ //服务代理(服务员) private IEat eatPerson; //定义吃饭的人 public EatProxy() { } public EatProxy(IEat eatPerson) { // 构造方法生成吃饭的人 this.eatPerson = eatPerson; } public IEat getEatPerson() { return eatPerson; } public void setEatPerson(IEat eatPerson) { this.eatPerson = eatPerson; } public void perpare(){ System.out.println("购买食材!"); System.out.println("处理食材!"); } public void clear() { System.out.println("收拾碗筷!!"); } @Override public void get() { this.perpare(); // 先准备食材 this.eatPerson.get(); // 服务员得到食物 this.clear(); // 结束清理 } }
package Demo_1_24_Proxy; public class ProxyTest { //主类 public static void main(String[] args) { IEat eat = new EatProxy(new EatReal()); eat.get(); } }