Design Patterns article

The mediator pattern

The proxy pattern

The bridge model

Abstract Factory Pattern details – Head First design pattern

Decorator pattern

Adapter mode

The strategy pattern

Observer model

Builder Mode

An overview of the

Definition of proxy mode: the proxy mode provides a proxy object to an object, and the proxy object controls the reference to the original object. Generally speaking, the agency model is a common intermediary in our life.

Problems with accessing objects directly, such as objects that are accessed on remote machines. In object-oriented systems, some object for some reason (such as the object creation overhead is very large, or some operations require safety control, or need to access) outside the process, will have direct access to caused a lot of trouble for the user or the system structure, during a visit to this object we can add an object to this access layer.

For example, if I want to buy a second-hand car, I can find the source of the car by myself, do quality inspection and a series of transfer procedures, but it is really a waste of my time and energy. Why do I have to go through all this extra work when I just want to buy a car? So I bought a car through an intermediary company. They would find a car source for me and help me with the transfer process. I was just responsible for choosing the car I liked and then paying for it.

Structure and implementation of proxy pattern

The structure of proxy mode is relatively simple, mainly by defining a proxy inheriting the abstract topic to contain the real topic, so as to realize the access to the real topic. The basic structure and implementation method are analyzed below.

The main roles of the proxy mode are as follows.

  1. Abstract Subject class: Business methods that declare real topics and proxy object implementations through interfaces or abstract classes.
  2. Real Subject class: Implements the concrete business in an abstract topic, is the Real object represented by the proxy object, and is the object ultimately referenced.
  3. Proxy class: Provides the same interface as a real topic, with internal references to real topics that can access, control, or extend the functionality of real topics.

Its structure is shown in the figure. \

Why use proxy mode?

  • Mediation isolation: In some cases, a client class may not want or be able to directly reference a delegate object, while a proxy object may act as an intermediary between the client and the delegate, characterized by the fact that the proxy and the delegate classes implement the same interface.
  • Open and close principle, add functionality: In addition to acting as an intermediary between the client class and the delegate class, we can also extend the functionality of the delegate class by adding additional functionality to the proxy class. In this way, we only need to modify the proxy class without modifying the delegate class, in accordance with the open and close principle of code design. The proxy class is responsible for pre-processing messages for the delegate class, filtering messages, forwarding messages to the delegate class, and post-processing the returned results. The proxy class itself does not actually implement the service, but rather provides specific services by calling the related methods of the delegate class. The real business functions are still implemented by delegate classes, but some common services can be added before and after the implementation of business functions. For example, if we want to add caching and logging to the project, we can use the proxy class to do so without opening the wrapped delegate class.

Definition and characteristics of the proxy pattern

The main advantages of the proxy model are:

  • Proxy mode plays an intermediary role and protects the target object between the client and the target object.
  • Proxy objects extend the functionality of target objects;
  • The proxy mode can separate the client from the target object, reduce the coupling degree of the system to a certain extent, and increase the scalability of the program

Its main disadvantages are:

  • The proxy pattern increases the number of classes in the system design
  • Adding a proxy object between the client and the target object slows down request processing.
  • Increased the complexity of the system;

What are the proxy modes?

There are many different ways to implement proxies. There are two types of agents: static agents and dynamic agents.

A static proxy is created by a programmer or a specific tool automatically generates source code before compiling it. The proxy class.class file is created before the programmer runs it. Dynamic proxies are created dynamically by reflection while the program is running.

Static proxy

**** Step 1: Create a service interface

package main.java.proxy;

public interface BuyHouse {
    void buyHosue();
}
Copy the code

Step 2: Implement the service interface

import main.java.proxy.BuyHouse; Public class BuyHouseImpl implements BuyHouse {@override public void buyHosue() {system.out.println (" I want to buy "); }}Copy the code

Step 3: Create the proxy class

package main.java.proxy.impl; import main.java.proxy.BuyHouse; public class BuyHouseProxy implements BuyHouse { private BuyHouse buyHouse; public BuyHouseProxy(final BuyHouse buyHouse) { this.buyHouse = buyHouse; } @override public void buyHosue() {system.out.println (); buyHouse.buyHosue(); System.out.println(" house after decoration "); }}Copy the code

Step 4: Write the test class

import main.java.proxy.impl.BuyHouseImpl; import main.java.proxy.impl.BuyHouseProxy; public class ProxyTest { public static void main(String[] args) { BuyHouse buyHouse = new BuyHouseImpl(); buyHouse.buyHosue(); BuyHouseProxy buyHouseProxy = new BuyHouseProxy(buyHouse); buyHouseProxy.buyHosue(); }}Copy the code

Static proxy summary:

Advantages: It can extend the function of the target object in accordance with the open and close principle.

Cons: We have to create proxy classes for each service, which is too much work to manage. Also, if the interface changes, the proxy class must be modified accordingly. * * * *

Dynamic proxy

In dynamic proxy we no longer need to manually create the proxy class, we just need to write a dynamic processor. The actual proxy objects are created dynamically for us by the JDK runtime.

For the implementation of dynamic proxies, as well as an analysis of the source code, see my previous article: Understanding Java Dynamic Proxies in Depth

Application scenarios of the proxy mode

After analyzing the structure and characteristics of the proxy pattern, let’s look at the following application scenarios.

  • Remote proxy, which is usually used to hide the fact that the target object exists in a different address space to facilitate client access. For example, when a user applies for some web disk space, a virtual disk is created in the user’s file system. When the user accesses the virtual disk, the user accesses the web disk space.
  • Virtual proxy, which is usually used when the target object to be created is expensive. For example, it takes a long time to download a large image, which cannot be completed in a short time due to some complicated calculation. In this case, the real object can be replaced with a small proportion of virtual agents to eliminate the user’s feeling of slow server.
  • Secure proxy, which is often used to control access to real objects by different types of clients.
  • Intelligence guidance, mainly used when calling the target object, with the agent adding some additional processing functions. For example, add the ability to count the number of references to a real object so that when the object is not referenced, it can be released automatically.
  • Lazy loading refers to delaying the loading of a target to improve system performance. Hibernate, for example, has lazy loading of attributes and lazy loading of associated tables.

The difference between proxy mode and decorator mode

Letting others help you with things you don’t care about is called the agency model

In order to enhance their ability, so that the enhanced themselves can use more methods, expand on their own based on the function, called the decorator mode.

For the decorator pattern, both the decorator and the decoratee implement the same interface.

For the proxy pattern, both the proxy class and the real class implement the same interface. The boundary between them is indeed fuzzy, both of which extend the methods of the class, the specific differences are as follows:

  1. The decorator pattern emphasizes enhancement itself, and after being decorated you can use enhanced functionality on the enhanced classes. Enhanced you will still be you, just more capable; The proxy model emphasizes having someone else do the work for you (logging, caching) that doesn’t have much to do with your business. The proxy pattern is intended to achieve control over objects because the propped objects are often difficult to obtain directly or do not want to be exposed internally.
  2. Decorator is an alternative to inheritance scheme, which extends the functions of objects transparently to clients. In the proxy mode, an object is provided with a proxy object, and the proxy object controls the reference to the original object.
  3. Decoration mode enhances the function of decorated objects; The proxy mode exerts control over the proxy object, but does not enhance the function of the object itself.