Agency model and some miscellaneous studies

Organize the knowledge

Adam Magee, senior solution architect at Avanade, said that the core idea of ​​AOP is to "separate the business logic in the application from the general services that support it."

Static proxy

Why is it static? Because of the static proxy, the proxy class is generated at compile time.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-nMAzwKcL-1616138782653)(images/image-20210319145217173.png)]

If the figurative point of view, if there is a tenant , the landlord , and intermediary three classes. The intermediary is the agent of the landlord, and the operation of renting a house is the common demand of the intermediary and the landlord (that is, the interface to be implemented).

Code:

//抽象角色:租房
public interface Rent {
    
    
   public void rent();
}
//真实角色: 房东,房东要出租房子
public class Host implements Rent{
    
    
   public void rent() {
    
    
       System.out.println("房屋出租");
  }
}
//代理角色:中介
public class Proxy implements Rent {
    
    

   private Host host;
   public Proxy() {
    
     }
   public Proxy(Host host) {
    
    
       this.host = host;
  }

   //租房
   public void rent(){
    
    
       seeHouse();
       host.rent();
       fare();
  }
   //看房
   public void seeHouse(){
    
    
       System.out.println("带房客看房");
  }
   //收中介费
   public void fare(){
    
    
       System.out.println("收中介费");
  }
}
//客户类,一般客户都会去找代理!
public class Client {
    
    
   public static void main(String[] args) {
    
    
       //房东要租房
       Host host = new Host();
       //中介帮助房东
       Proxy proxy = new Proxy(host);
       //租客去找中介!
       proxy.rent();
  }
}

In this process, the direct contact is the intermediary, just like in real life, the landlord cannot be seen, but the landlord’s house is still rented through an agency. This is the so-called agency model.

Benefits of static proxy:

  • It can make our real role more pure. No longer pay attention to some public things. (The landlord only pays attention to the preparation of the house, and the other things are left to the intermediary, high cohesion, low coupling)
  • The public business is completed by the agent. The division of labor is realized,
  • When public business expands, it becomes more centralized and convenient.

Disadvantages:

  • There are more classes and more agent classes, and the workload becomes larger. Development efficiency is reduced.

We want the benefits of static proxy, but don't want the disadvantages of static proxy, so we have dynamic proxy!

We have realized the enhancement of the original function without changing the original code, which is the core idea in AOP

Dynamic proxy

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-BwlPgtj3-1616138782653)(images/image-20210319150336946.png)]

  • The role of dynamic agents is the same as that of static agents.
  • The proxy class of the dynamic proxy is dynamically generated. The proxy class of the static proxy is written in advance by us
  • Dynamic agents are divided into two categories: one is dynamic agents based on interfaces, and the other is dynamic agents based on classes.

​ JDK dynamic proxy (essentially implemented by reflection)

Object invoke(Object proxy, 方法 method, Object[] args)//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。
public class ProxyInvocationHandler implements InvocationHandler {
    
    
    private Object target;

    public void setTarget(Object target) {
    
    
        this.target = target;
    }

    //生成代理类
    public Object getProxy(){
    
    
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                                      target.getClass().getInterfaces(),this);
    }

    // proxy : 代理类
    // method : 代理类的调用处理程序的方法对象.
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
        log(method.getName());
        Object result = method.invoke(target, args);
        return result;
    }

    public void log(String methodName){
    
    
        System.out.println("执行了"+methodName+"方法");
    }

}
public class Test {
    
    
   public static void main(String[] args) {
    
    
       //真实对象
       UserServiceImpl userService = new UserServiceImpl();
       //代理对象的调用处理程序
       ProxyInvocationHandler pih = new ProxyInvocationHandler();
       pih.setTarget(userService); //设置要代理的对象
       UserService proxy = (UserService)pih.getProxy(); //动态生成代理类!
       proxy.delete();
  }
}
Benefits of dynamic proxy

Some static agents have it, and static agents do not have it!

  • Can make our real role more pure. No longer pay attention to some public things.
  • The public business is completed by the agent. The division of labor is realized,
  • When public business expands, it becomes more centralized and convenient.
  • A dynamic agent, general agent for a certain type of business
  • A dynamic proxy can proxy multiple classes, and the proxy is an interface!

So what is AOP?

Explain what is aop?

AOP (Aspect-Oriented Programming, aspect-oriented programming) can be said to be the complement and improvement of OOP (Object-Oriented Programming, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to establish a hierarchy of objects to simulate a collection of public behaviors. When we need to introduce public behaviors for scattered objects, OOP is powerless. In other words, OOP allows you to define a top-to-bottom relationship, but it is not suitable for defining a left-to-right relationship. For example, the log function. Log code is often distributed horizontally in all object levels, and has nothing to do with the core functions of the objects it is distributed to. The same is true for other types of code, such as security, exception handling, and transparent persistence. This kind of irrelevant code scattered everywhere is called cross-cutting code. In OOP design, it leads to a lot of code duplication, which is not conducive to the reuse of various modules.

The AOP technology is just the opposite. It uses a technology called "cross-cutting" to dissect the inside of the encapsulated object, and encapsulate those common behaviors that affect multiple classes into a reusable module, and name it. For "Aspect", that is, aspect. The so-called "aspect", simply put, is to encapsulate the logic or responsibilities that are not related to the business, but are called by the business modules, which is convenient for reducing the repetitive code of the system, reducing the coupling between modules, and is conducive to future development. Operability and maintainability. AOP represents a horizontal relationship. If the "object" is a hollow cylinder, which encapsulates the properties and behaviors of the object; then the method of aspect-oriented programming is like a sharp edge to split these hollow cylinders. Open to get the news inside. The cut section is the so-called "aspect". Then it restored these cut planes with ingenious skill, leaving no traces.

Using "cross-cutting" technology, AOP divides the software system into two parts: core concerns and cross-cutting concerns. The main process of business processing is the core concern, and the less relevant part is the crosscutting concern. One characteristic of crosscutting concerns is that they often occur in multiple places of the core concern, and they are basically similar everywhere. Such as authority authentication, log, transaction processing. The role of Aop is to separate the various concerns in the system and separate the core concerns from the cross-cutting concerns. As Adam Magee, senior solution architect of Avanade, said, the core idea of ​​AOP is to "separate the business logic in the application from the general services that support it."

Tips: Some associations and reviews

When it comes to static proxy and dynamic proxy, I can't help thinking of static binding and dynamic binding, as well as overloading and rewriting, so I can review it.

Overloading means that multiple methods with the same name are allowed, and the parameters of these methods are different. The compiler modifies the name of the method with the same name according to the different parameter tables of the method. For the compiler, these methods with the same name become different methods. Their call addresses are bound at compile time. Java overloading can include parent classes and subclasses, that is, subclasses can override methods with the same name and different parameters of the parent class.
Therefore: for overloading, the compiler has already determined the method to be called before the method is called. This is called "early binding" or "static binding";

For polymorphism, the interpreter will only determine the specific method to be called only when the method is called. This is called "late binding" or "dynamic binding".

To quote Bruce Eckel: "Don't be stupid, if it's not late binding, it's not polymorphic."

Thinking of polymorphism, I also thought of some differences between JAVA's virtual function call and C++.

In C++, polymorphism is realized by way of virtual function table. Each class containing virtual functions has a virtual table (virtual table), and the pointer to the virtual function table is stored at the top of the address space of this class object Pointer. In the virtual function table, all virtual functions are arranged in the order of declaration.

In fact, the virtual function table in C++ records the specific implementation of all virtual functions of this class (that is, the exact call to be called at runtime), which can be determined at compile time, and there is no need for dynamic search, which is more efficient.


In Java, the type information and class inheritance system are maintained at runtime. Each class corresponds to a data structure in the method area for storing class information, and this data structure can be accessed through the Class object. Among them, the type information has a superclass attribute indicating its superclass and the corresponding method table of this class (which only contains the methods defined by this class, excluding those inherited from the superclass). And every object created on the heap has a pointer to the method area type information data structure, through which the type of the object can be determined.

The implementation of Java depends on the type system information in the memory. There is a "prototype chain", which is a completely dynamic search process. Compared with C++, the efficiency is lower because there is a linked list traversal search process. The reason why this can be implemented in Java is essentially because it is a virtual machine language, and the virtual machine maintains all these types of information.

Guess you like

Origin blog.csdn.net/weixin_43615816/article/details/115007448