2021 autumn recruitment interview computer foundation summary – algorithm, data structure, design pattern, Linux

Time:2021-1-18

algorithm

Binary tree

Several different algorithms can be used to calculate the height of binary tree.

Algorithm 1: traversing the binary tree in the latter order, the maximum stack length of the node is the height of the binary tree;

Algorithm 2: traverse the binary tree hierarchically, and the maximum level is the height of the binary tree;

Algorithm 3: using recursive algorithm to find the height of binary tree.

class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}

public int height(TreeNode p) {  //P is a reference to the root node of a binary tree
    if(p == null){
       return 0;
     }else{
       return 1 + max(height(p.left),height(p.right));
     }
}
Full binary tree

For a binary tree, if every non leaf node has left and right subtrees, and all leaf nodes in the binary tree are in the same layer, such a binary tree is called full binary tree.

Complete binary tree

For a binary tree with n nodes, it is numbered according to the hierarchy, and the left and right subtrees are numbered according to the first left and then the right. If the node named II is exactly the same as the node named II in the full binary tree of the same depth, the binary tree is called a complete binary tree.

BST

If its left subtree is not empty, the values of all nodes on the left subtree are less than the values of its root node; if its right subtree is not empty, the values of all nodes on the right subtree are greater than the values of its root node; its left and right subtrees are also binary sort trees.

AVL tree (balanced binary search tree)

AVL tree is a binary search tree with balance condition. It usually uses the balance factor difference to judge whether it is balanced or not, and realizes the balance by rotation. Compared with red black tree, AVL tree is a binary search treeStrictly balanced binary treesThe equilibrium condition must satisfy:The absolute value of height difference between left and right subtrees of all nodes is less than 1. No matter whether we are performing the insert or delete operation, as long as the above conditions are not met, we need to maintain the balance through rotation, which is very importanttime consumingFrom this we can knowAVL tree is suitable for the case of less insertion and deletion times but more search times

limitations

Because the cost of maintaining this high balance is greater than the efficiency gains from it, there are not many practical applications, and more places are to use the red black tree which pursues partial balance rather than very strict overall balance. of course,If the insertion and deletion are not frequent in the application scenario, but the search requirement is high, then AVL is better than red black tree.

application

Windows management of process address space

Red black tree

A binary search tree, which adds a storage bit to each node to indicate the color of the node, which can be red or black(Either red or black)。 By limiting the way of coloring each node on any path from root to leaf,The red black tree ensures that no path is twice as long as the othersTherefore, the red black tree is a kind of treeWeakly balanced binary tree(since it is a weak equilibrium, we can see that,In**Under the same node, the height of AVL tree is lower than that of red black treeCompared with the strict AVL tree, it has less rotation times, soFor search, insert and delete operations, we use red black tree * *.

nature

1. Each node is either red or black;

2. The root node is black;

3. Every leaf node is black;

4. If a node is red, its two sons are black;

5. For any node, each path to the null pointer of the leaf tree contains the same number of black nodes;

application

Storage structure of treemap and HashMap

Sorting algorithm

  • classification

    • Sorting algorithms can be divided intoInternal sortingandExternal sortingWhen the amount of data to be sorted is large, it can’t be copied to memory completely, so it needs to use external memory to sort. This sort is called external sort.
    • Internal sortingIt includes comparison sort and non comparison sort. Comparison sort includes insertion sort, selection sort, exchange sort and merge sort. Non comparison sort includes count sort, cardinality sort and bucket sort. Insert sort includes direct insert sort and Hill sort, select sort includes direct select sort and heap sort, exchange sort includes bubble sort and quick sort.
  • Stability: if the relative position of two equal numbers before and after sorting is unchanged, the algorithm is stable.

    • instable: heap sort, quick sort, Hill sort, direct select sort
    • stable: sort algorithm of cardinal sort, bubble sort, direct insert sort, half insert sort and merge sort.

Direct insertion sort

one kindstableWhen the elements are basically ordered, the best time complexity is O (n) and the space complexity is O (1).

  • Basic principle:

    Each time, a record to be sorted is inserted into the appropriate position of a group of records that have been sorted according to the size of its keyword until all the records to be sorted are inserted. It is suitable for the situation that there are few records to be sorted or basically ordered.
public class InsertSort {
    public static int[] insertSort(int[] arr) {
        if(arr == null || arr.length < 2)
            return arr;

        int n = arr.length;
        for (int i = 1; i < n; i++) {
            int temp = arr[i];
            int k = i - 1;
            while(k >= 0 && arr[k] > temp)
                k--;
            //The position to be inserted is K + 1;
            for(int j = i ; j > k + 1; j--)
                arr[j] = arr[j-1];
            //Put it in
            arr[k+1] = temp;
        }
        return arr;
    }
}

Shell Sort

It belongs to insert sort, also known as reducing incremental sort, which is an improvement of direct insert sort and a new sortinstableThe average time complexity is O (n ^ 1.3), the worst time complexity is O (N 2), the best time complexity is O (n), and the space complexity is O (1).

  • The basic principle is as follows:

    The records are grouped according to a certain increment of subscript, and the elements of each group are directly inserted and sorted. After each sorting, the increment is reduced to regroup. When the increment is reduced to 1, the sorting is completed. It is suitable for medium-sized data volume, but it is not the best choice for very large data volume.
public class ShellSort {
    public static int[] shellSort(int arr[]) {
        if (arr == null || arr.length < 2) return arr;
        int n = arr.length;
        //At the beginning, H = n / 2;
        for (int h = n / 2; h > 0; h /= 2) {
            //Insert and sort each bureau group
            for (int i = h; i < n; i++) {
                //Insert arr [i] into the correct position of the group
                insertI(arr, h, i);
            }
     }
     return arr;
    }

    /**
    private static void insertI(int[] arr, int h, int i) {
        int temp = arr[i];
        int k;
        for (k = i - h; k > 0 && temp < arr[k]; k -= h) {
            arr[k + h] = arr[k];
        }
        arr[k + h] = temp;
    }
}

Select sort

one kindinstableIn any case, the time complexity is O (N 2) and the space complexity is O (1).

  • Basic working principle:

    First, find the smallest element in the unordered sequence and store it at the beginning of the sorted sequence. Then, continue to find the smallest element from the remaining unordered elements and put it at the end of the sorted sequence. And so on, until all elements are sorted.
public class SelectSort {
    public static int[] selectSort(int[] a) {
        int n = a.length;
        for (int i = 0; i < n - 1; i++) {
            int min = i;
            for (int j = i + 1; j < n; j++) {
                if(a[min] > a[j]) min = j;
            }
            //Exchange
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        return a;
    }
}

Heap sort

It belongs to selective sorting, which is an improvement of direct selective sorting, and it is also a new methodinstableIn any case, the time complexity is O (nlogn) and the space complexity is O (1). Initialize build o (n); reorder build o (nlogn).

  • The basic principle is to treat the records to be sorted as a complete binary tree.

    • Build the unnecessary sequence into a heap, and select the big top heap or the small top heap according to the ascending and descending requirements
      • The characteristics of the big top heap: the value of each node is greater than or equal to the value of its left and right child nodes. After the big top heap is built, the value of the root node must be the largest, and then the root node and the last element (that is, the last node) are exchanged, so the last element is the largest element
    • Exchange the top element of the heap with the end element, and sink the largest element to the end of the array
    • Restructure it to meet the heap definition, and then continue to exchange the top elements with theCurrent end elementThe adjustment + exchange steps are repeated until the whole sequence is in order.
  • By default, the minimum element of PriorityQueue comes first

    • adopt(a - b) -> b - aChange to descending output
public class Head {
    //Heap sort
    public static int[] headSort(int[] arr) {
        int n = arr.length;
        //Construction of large top reactor
        for (int i = (n - 2) / 2; i >= 0; i--) {
            downAdjust(arr, i, n - 1);
        }
        //Do heap sort
        for (int i = n - 1; i >= 1; i--) {
            //Swap the top element with the last one
            int temp = arr[i];
            arr[i] = arr[0];
            arr[0] = temp;
            //Adjust the disordered heap to restore the characteristics of the heap
            downAdjust(arr, 0, i - 1);
        }
        return arr;
    }

        //Sinking operation
    public static void downAdjust(int[] arr, int parent, int n) {
        //Temporarily save the element to sink
        int temp = arr[parent];
        //Locate the left child node
        int child = 2 * parent + 1;
        //It began to sink
        while (child <= n) {
            //If the right child node is larger than the left child, navigate to the right child
            if(child + 1 <= n && arr[child] < arr[child + 1])
                child++;
            //If the child node is less than or equal to the parent node, the sink ends
            if (arr[child] <= temp ) break;
            //The parent node sinks
            arr[parent] = arr[child];
            parent = child;
            child = 2 * parent + 1;
        }
        arr[parent] = temp;
    }
}

Bubble sort

Bubble sort belongs to commutative sort, which is a new sortinstableWhen the elements are basically ordered, the best time complexity is O (n) and the space complexity is O (1).

The basic principle is: it repeatedly visits the sequence to be sorted, compares two elements at a time, and exchanges them if they are in the wrong order. The work of visiting the sequence is repeated until there is no need to exchange, that is to say, the sequence has been sorted.

public class BubbleSort {
    public static int[] bubbleSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return arr;
        }
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            boolean flag = true;
            for (int j = 0; j < n -i - 1; j++) {
                if (arr[j + 1] < arr[j]) {
                    flag = false;
                    int t = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = t;
                }
            }
            //Is there a location exchange
            if(false)
                break;
        }
        return arr;
    }
}

Quick sort

The average time complexity and the best time complexity are o (nlogn). When the elements are basically ordered, the worst time complexity and the space complexity are o (logn).

  • The basic principle is as follows:

    Select an element from the array as the axis element, and then put all the elements in the array that are less than the axis element on the left, and all the elements that are greater than or equal to the axis element on the right.

    Then the position of the axis element is in order. That is to say, we don’t need to move the position of the axis element any more.)

    Starting from the middle axis element, the large array is cut into two small arrays (both arrays do not contain the middle axis element). Then, by recursion, the left and right arrays of the middle axis elements repeat the same operation until the size of the array is 1, and each element is in an orderly position.
public class QuickSort {
    public static int[] quickSort(int[] arr, int left, int right) {
        if (left < right) {
            //Gets the position of the axis element
            int mid = partition(arr, left, right);
            //Split
            arr = quickSort(arr, left, mid - 1);
            arr = quickSort(arr, mid + 1, right);
        }
        return arr;
    }

    private static int partition(int[] arr, int left, int right) {
        //Select axis element
        int pivot = arr[left];
        int i = left + 1;
        int j = right;
        while (true) {
            //To the right, find the position of the first element less than or equal to pivot
            while (i <= j && arr[i] <= pivot) i++;
            //Find the position of the first element greater than or equal to pivot to the left
            while(i <= j && arr[j] >= pivot ) j--;
            if(i >= j)
                break;
            //Swap the positions of the two elements so that the element on the left is not greater than pivot and the element on the right is not less than pivot
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        arr[left] = arr[j];
        //Make the axis elements in an orderly position
        arr[j] = pivot;
        return j;
    }
}

Merge sort

Merge sort is a sort algorithm based on merge operation. It is a stable sort algorithm. In any case, the time complexity is O (nlogn) and the space complexity is O (n).

  • Basic principles

    Divide and conquer method is applied to divide the sequence to be sorted into two parts, then recursively sort the two parts respectively, and finally merge them. An auxiliary space is used and two pointers are set to point to the starting elements of the two ordered sequences respectively. The smaller elements corresponding to the pointers are added to the auxiliary space. Repeat this step until one sequence reaches the end, and then merge the remaining elements of another sequence into the auxiliary space At the end of the space. It is suitable for the case of large amount of data and the requirement of stability.

Recursion:

public class MergeSort {
    //Merge sort
    public static int[] mergeSort(int[] arr, int left, int right) {
        //If left = = right, there is only one element in the array, there is no recursive sorting
        if (left < right) {
            //Separate a large array into two arrays
            int mid = (left + right) / 2;
            //Sort the left half
            arr = mergeSort(arr, left, mid);
            //Sort the right half
            arr = mergeSort(arr, mid + 1, right);
            //Merge
            merge(arr, left, mid, right);
        }
        return arr;
    }

    //Merge function to merge two ordered arrays
    //Arr [left.. MIF] represents an array, and arr [mid + 1.. right] represents an array
    private static void merge(int[] arr, int left, int mid, int right) {
        //First, combine them with a temporary array
        int[] a = new int[right - left + 1];
        int i = left;
        int j = mid + 1;
        int k = 0;
        while (i <= mid && j <= right) {
            if (arr[i] < arr[j]) {
                a[k++] = arr[i++];
            } else {
                a[k++] = arr[j++];
            }
        }
        while(i <= mid) a[k++] = arr[i++];
        while(j <= right) a[k++] = arr[j++];
        //Copy the temporary array to the original array
        for (i = 0; i < k; i++) {
            arr[left++] = a[i];
        }
    }
}

Non recursive:

public class MergeSort {
    //Non recursive merge sort
    public static int[] mergeSort(int[] arr) {
        int n = arr.length;
        //The subarrays are 1, 2, 4, 8
        //The initial merged array size is 1, then 2, then 4
        for (int i = 1; i < n; i += i) {
            //Divide the array
            int left = 0;
            int mid = left + i - 1;
            int right = mid + i;
            //To merge, merge the arrays with the size of I in pairs
            while (right < n) {
                //Merge functions are the same as recursive merge functions
                merge(arr, left, mid, right);
                left = right + 1;
                mid = left + i - 1;
                right = mid + i;
            }
            //There are still some missing arrays that haven't been merged. Don't forget
            //Because it is impossible for each word group to be exactly I
            if (left < n && mid < n) {
                merge(arr, left, mid, n - 1);
            }
        }
        return arr;
    }
}

Design pattern

Principles of design pattern

Principle of opening and closing:In object oriented designMost basicThe design principle refers to aSoftware entities (classes, modules, methods, etc.) should be open to extensions and closed to modifications. It emphasizes building framework with abstraction, extending details with implementation, and improving reusability and maintainability of code. For example, when the version is updated, try not to modify the source code, but you can add new features.

Single responsibility principle: A class, interface, or method has only one responsibilityIt can improve code readability and maintainability, reduce code complexity and the risk caused by changes.

The principle of Dependence Inversion: Programs should rely on abstract classes or interfaces, not concrete implementation classes. It can reduce the code coupling and improve the stability of the system.

Interface isolation principle: Define different functions in different interfacesThe implementation of interface isolation avoids class dependence on interfaces it does not need, and reduces the redundancy and complexity of dependencies between interfaces.

Richter’s replacement principle:A supplement to the open close principle,It stipulates that any place where the parent class can appear, the subclass must appearIt can restrict the overflow of inheritance and the robustness of keying program.

Dimiter principle:At least know the principle,Each module should have as little knowledge and dependence on other modules as possibleTo reduce code coupling.

Principles of synthesis / polymerization: Try to use combination (has a) or aggregation (contains a) instead of inheritance relationship to achieve the purpose of software reuseIt can make the system more flexible and reduce the coupling degree.

Classification of design patterns

Creative mode:It provides a way to hide the creation logic while creating objects, instead of using the new operator to instantiate objects directly, which makes the program more flexible in judging which objects need to be created for a given instance. It includes: factory mode, abstract factory mode, singleton mode, builder mode and prototype mode.

Structural mode:Through the inheritance and reference between class and interface, the function of creating complex structure object is realized. Including: adapter mode, bridge mode, filter mode, combination mode, decorator mode, appearance mode, sharing mode, agent mode.

Behavior model: the behavior modelDifferent ways of behavior are realized by different ways of communication between classes. It includes: responsibility chain mode, naming mode, interpreter mode, iterator mode, mediator mode, memo mode, observer mode, state mode, strategy mode, template mode and visitor mode.

Examples of several modes

Simple factory model

Concept:The instance is created by a factory object. The client does not need to pay attention to the creation logic, but only needs to provide the parameters passed into the factory.

Scene:It is suitable for the case that the factory class is responsible for creating fewer objects. The disadvantage is that if you want to add new products, you need to modify the judgment logic of the factory class, which violates the open close principle.

give an example:

  • Of the calendar classgetInstanceMethod, callingcreateCalendarMethod to create different calendar objects according to different region parameters.
  • Beanfactory in spring obtains the bean instance by passing in a unique ID.

Factory method model

Concept: Provide different factories for different objects.Define an interface to create an object, let the implementation class of the interface decide which object to create, and postpone the instantiation of the class to the subclass.

Scene:It mainly solves the problem of product expansion. In the simple factory mode, if there are more kinds of products, the responsibilities of the factory will be more and more, which is not easy to maintain.

give an example:

  • The collection interface defines an abstractiteratorFactory method, which returns an abstract product of the iterator class. This method is implemented by specific factories such as ArrayList and HashMap, and returns specific products such as ITR and keyiterator.
  • Design of factorybean interface in springgetObjectmethod.

Abstract factory pattern

Concept: The factory class in this pattern can not only create one object, but also create a group of objects. Each specific factory provides multiple factory methods to generate a variety of different types of objects.Provides an interface to create a series of related objects without specifying their specific classes. The disadvantage is that it is not convenient to expand the product family, and it increases the abstraction and understanding difficulty of the system.

Scene:When a group of objects need to complete a certain function together, and there may be multiple groups of objects to complete different functions. The system structure is stable, and objects will not be added frequently.

give an example: java.sql.Connection Interface is an abstract factory, which includes many abstract products, such as statement, blob, savepoint, etc.

Singleton mode

In any case, there is only one instance, the construction method must be private (cannot be inherited), create a static variable storage instance by itself, and provide a static public method to obtain the instance.

The advantage is that there is only one instance in memory, which reduces the cost; the disadvantage is that there is no abstract layer, which is difficult to expand, and the responsibility of singleton class is too heavy, which conflicts with the principle of single responsibility.

For example: bean instances created by spring’s ApplicationContext are singleton objects, as well as ServletContext and database connection pool.

Starving Han style:The singleton object is created when the class is loaded, which is thread safe, but the object is created regardless of whether it is used or not. Memory may be wasted.

Moreover, if the creation of singleton instance depends on parameters or configuration files, you must call a method to set parameters to it before getinstance(), then this singleton instance writing method cannot be used.

public class Singleton {
    private Singleton(){}
    private static Singleton instance = new Singleton();
    public static Singleton getInstance() {
        return instance;
    }
}

Lazy style:It will be loaded only when it is called externally. When multiple threads call getinstance() in parallel, multiple instances will be created. Threads are not safe, and locks can be added to ensure thread safety, but the efficiency is low. Because only one thread can call the getInstance () method at any time.

public class Singleton {
    private Singleton(){}
    private static Singleton instance;
    public static Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Double check lock:Synchronous operation is only needed when it is called for the first time. Volatile and multiple checks are used to reduce the lock range and improve efficiency.

public class Singleton {
    private Singleton(){}
    private volatile static Singleton instance;
    public static Singleton getInstance() {
        if(instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Why do I have to check again in the synchronization block?Because multiple threads may enter the if outside the synchronization block together, multiple instances will be generated if there is no secondary check in the synchronization block.

Volatile action

solveinstance = new Singleton()The problem with this sentence: non atomic operation.

In fact, in the JVM, this sentence probably does the following three things. However, there is an optimization of instruction reordering in the just in time compiler of the JVM. In other words, the order of the second and third steps above cannot be guaranteed.

  1. Allocate memory for instance
  2. Call Singleton’s constructor to initialize member variables
  3. Point the instance object to the allocated memory space (after this step, the instance will be non null)

Volatile can be used to prevent instruction reordering optimization. In other words, there will be a memory barrier (on the generated assembly code) after the assignment operation of volatile variables, and the read operation will not be reordered before the memory barrier. For example, in the above example, the fetching operation must be performed after 1-2-3 or 1-3-2. There is no case of fetching values after 1-3.

Static inner class:At the same time, it solves the problem of starving memory waste and lazy thread safety.

This writing method uses the mechanism of the JVM itself to ensure the thread safety problem: during the initialization phase of the execution class, the JVM will obtain a synchronization lock to ensure the thread safety when multiple threads initialize the same class; since staticclass is private, except getInstance () There is no way to access it outside, so it is lazy; at the same time, the instance is read without synchronization, and there is no performance defect

public class Singleton {
    private Singleton(){}
    public static Singleton getInstance() {
        return StaticClass.instance;
    }
    private static class StaticClass {
        private static final Singleton instance = new Singleton();
    }
}

Enumeration:The method advocated by effective Java can not only avoid thread safety problems, but also prevent deserialization from re creating new objects, and also prevent reflection from cracking singletons.

public enum Singleton {
    INSTANCE;
}

proxy pattern

Proxy pattern is a structural pattern, which provides a proxy for other objects to control the access to the object. The advantage is that it can enhance the function of the target object and reduce the code coupling; the disadvantage is that the request processing speed is slow and the system complexity is increased.

Static agent:The proxy object holds the reference of the proxy object. When the proxy object method is called, the method of the proxy object will be called, but other logic will be added. It needs to be done manually. The bytecode file of the proxy class already exists before the program runs. The relationship between the proxy class and the proxy class has been determined before the program runs. The disadvantage is that a proxy class can only serve one target.

Dynamic agent:The dynamic agent passes through thereflexTo create a concrete proxy class, the relationship between the proxy class and the proxy class is uncertain before running. Dynamic agent is more applicable, mainly divided into JDK dynamic agent and cglib dynamic agent.

  • JDK agent:

    By proxynewProxyInstanceMethod to get the proxy object, we need three parameters: the interface of the proxy class, the class loader and the invocationhandler object. We need to override the invoke method of the invocationhandler interface to indicate the proxy logic.
  • Cglib agent:

    Through enhancer objectcreateMethod to get the proxy objectsetSuperclassMethod to set the proxy class, andsetCallbackMethod indicates the proxy logic (pass in an implementation class of the methodinterceptor interface, and the specific proxy logic is declared in theinterceptMethods).

    JDK dynamic proxy writes stanza code directly, while cglib dynamic proxy uses ASM framework to write stanza code. JDK proxy calls proxy method through reflection, while gclib uses fastclass mechanism to generate a class for proxy class and proxy class respectively. This class allocates an int parameter for the methods of proxy class and proxy class. When calling method, it can locate directly and has higher efficiency.

Decorator mode

Concept:It is more flexible than inheritance to attach functions to objects without changing the original objects.

Scene:Extend the function of a class without adding many subclasses.

give an example:java.io In the package, InputStream is enhanced to buffered byte input stream by buffered InputStream.

The difference between agent mode and agent mode is as followsDecorator Pattern focuses on adding methods to objects dynamically, while dynamic proxy pays more attention to object access control.Dynamic proxies usually create instances of the proxied object in the proxy class, while decorator mode takes the decorator as a parameter of the construction method.

Adapter mode

Concept:As a bridge between two incompatible interfaces, classes that could not work together because of interface incompatibility can work together. The disadvantage is that too much use of adapter will make the system very chaotic and difficult to grasp as a whole.

give an example:

  • java.io In the package, InputStream is converted to reader character input stream through inputstreamreader.
  • The handleradapter in spring MVC has many forms, including controller, httprequesthandler, servlet and so on, but the calling mode is determined. Therefore, the adapter is needed to process it and call the handle method according to the adaptation rules.
  • Arrays.asList Method to convert the array to the corresponding collection (you cannot modify the collection because the returned ArrayList is an internal class of arrays).

The difference between adapter mode and decorator mode: adapter mode has no hierarchical relationship, adapter and Adaptee are not necessarily continuous, it is a post consideration to meet the has-a relationship and solve the problem of incompatibility; decorator mode has hierarchical relationship, decorator and decoratee realize the same interface, meet the is-a relationship, pay attention to coverage and expansion, it is a pre consideration.

The difference between adapter mode and proxy mode: adapter mode mainly changes the interface of the object under consideration, while proxy mode cannot change the interface of the class under proxy.

Strategy model

Concept:A series of algorithms are defined and encapsulated, which can replace each other. The advantage is that the algorithm can switch freely, avoid using multiple condition judgment and has good scalability. The disadvantage is that the policy classes will increase and all policy classes need to be exposed.

Scene:It mainly solves the problem that if / else is difficult to maintain when there are many similar algorithms.

give an example:

  • Comparator, which is commonly used in collection framework, is an abstract policy. A class becomes a concrete policy class by implementing the interface and rewriting the compare method.
  • Deny policy for thread pool.

Template mode

Concept:The subclass can redefine some steps of the algorithm without changing the structure of the algorithm. The advantage is that it can encapsulate the fixed part and expand the variable part; the disadvantage is that each different implementation needs a subclass maintenance, which will increase the number of classes.

Scene:It is suitable for extracting repeated code from subclass to common parent class.

For example: httpservlet defines a set of templates for processing HTTP requests, service method is the template method, defines the basic process for processing HTTP requests, doxxx and other methods are the basic methods, and processes them according to the types of request methods. Subclasses can override these methods.

Observer model

Concept:Also known as publish subscribe mode, it defines a one to many dependency relationship between objects. When the state of an object changes, all the objects that depend on it are notified and automatically updated. The disadvantage is that if the observed object has many direct and indirect observers, the notification is time-consuming. If there is a circular dependency, the system may crash. In addition, the observer cannot know how the target object changes.

Scene:It mainly solves the problem of notifying other objects when the state of one object changes.

For example: servletcontextlistener can listen to the life cycle of ServletContext object, which is actually listening to web application. Called when the servlet container starts the web applicationcontextInitializedMethod, called on terminationcontextDestroyedmethod.

Linux command

Linux commands used in the deployment project:

1. Enter the bin directory of Tomcat cd /data/apache-tomcat-6.0.39/bin

2. Check the process of Tomcat ps -ef | grep tomcat

3. Kill processKill – 9 + number of processes

View process 2.1, PS – EF | grep XX 2.2, PS – aux | grep XXX (- aux shows all status)

View port: 1. Netstat – ANP | grep port number (the status of listen indicates occupied)

4. Start the project sh startup.sh

5. Permanently delete files

RM – RF * delete all files in the current directory. This command is very dangerous and should be avoided. Delete the file, generally can not restore! ;

In RM – F, the f parameter (f – force) ignores nonexistent files and does not display any information

6. Copy filesCP RF original path / destination path/

7. Compressed folder

Decompression: tar zxvf FileName.tar.gz

Compression: tar zcvf FileName.tar.gz DirName

8. Unzip (install zip command)*Unzip package

9. MobileMV + path / file + path to move to

SCP – R directory name remote computer user name @ remote computer IP: the path where the remote computer stores the directory

10. Switching usersSu user name

This work adoptsCC agreementReprint must indicate the author and the link of this article