Ways to implement static proxy

Implementation steps:
1. Create an interface, define a method, and express what the target and agent need to do.

package com.itweiting.service;
public interface ThreeSquirrelSell {
    
    
     //定义方法 参数amount表示一次购买的数量
     //返回值表示优盘的价格
         float sell(int amount);
     //可以定义多个方法
}

2. Create the target class and implement the interface

package com.itweiting.factory;
import com.itweiting.service.ThreeSquirrelSell;
public class ThreeSquirrelFactory implements ThreeSquirrelSell{
    
    
    //目标类,厂家,厂家不接受用户的单独购买
    public float sell(int amount) {
    
    
        //一包零食的价格
        //后期根据amount数量进行调整价格,例如一箱零食100元,买两箱零食每箱90元
        return 100.0f;
    }
}

3. Create an agent and implement an interface (enhanced functions are realized)

package com.itweiting.shangjia;
import com.itweiting.factory.ThreeSquirrelFactory;
import com.itweiting.service.ThreeSquirrelSell;
//淘宝进行代理销售,
public class Taobao implements ThreeSquirrelSell {
    
    


    //声明商家代理的厂家是谁
    private ThreeSquirrelFactory factory=new ThreeSquirrelFactory();
    //实现销售的功能
    public float sell(int amount) {
    
    
        //向厂家发送订单,提醒厂家进行发货
        float price = factory.sell(amount);
        /*功能增强*/
        //商家进行加价,(即代理进行后期的加价)
        //代理类完成了目标类的方法调用后增加了其他功能(比如增减价格)
        price = price+25;
        //优惠
        System.out.println(price-20);
        //返回增加价格后的商品价格
        return price;
    }
}

4. Create a client class and call the agent to perform an operation.

package com.itweiting;
import com.itweiting.shangjia.Taobao;
public class ShopMain {
    
    
    public static void main(String[] args) {
    
    
        //创建淘宝的代理对象
        Taobao taobao =new Taobao();
        float price=taobao.sell(1);
        System.out.println(price);
    }
}

The functions completed by the proxy class: 1. Calling the target class method 2. Realizing the enhancement of the function


Guess you like

Origin blog.csdn.net/qq_44143902/article/details/110260926