Java开发设计模式之代理模式

2020-06-17  本文已影响0人  伪装的狼

public class ProxyMode {

public static void main(String[] args) {
    //代理模式
    Drink drink = new DrinkProxy(new DrinkReal());
    drink.get();
}

}

interface Drink{ //定义核心业务标准
void get(); //定义主要执行方法
}

class DrinkReal implements Drink{
@Override
public void get() {
System.out.println("开始喝水果汁了!");
}
}

class DrinkProxy implements Drink{

private Drink mDrink;

public DrinkProxy(Drink drink){
    mDrink = drink;
}

@Override
public void get() {
    this.prepare();
    this.squeezedFruit();
    mDrink.get();   //喝水果汁,执行主要步骤
}

private void prepare(){
    System.out.println("清洗水果!");
    System.out.println("清洗榨汁机!");
}

private void squeezedFruit(){
    System.out.println("榨水果汁!");
}

}

/*

//如果工厂模式与代理模式相结合就是

class FactoryFruit{
public static Drink getInstance(){
return new DrinkProxy(new DrinkReal());
}
}

//把获取实例改成从工厂获取
public class ProxyMode {

public static void main(String[] args) {
    //工厂模式 + 代理模式
    Drink drink = FactoryFruit.getInstance();
    drink.get();
}

}

上一篇下一篇

猜你喜欢

热点阅读