Mr. Cappuccino's 18th cup of coffee -- design mode of gold, silver and four-sided test questions

Posted by nitediver on Sat, 26 Feb 2022 11:18:56 +0100

1. Why do you need to use design patterns?

Using design patterns to reconstruct the whole code can improve the reusability and scalability of the code and reduce code redundancy.

2. Talk about the six principles of design mode?

  1. Open Close Principle: the Open Close Principle is open to extensions and closed to modifications. When the program needs to be expanded, you can't modify the original code to achieve a hot plug effect. So in a word: in order to make the program extensible, easy to maintain and upgrade. To achieve this effect, we need to use interfaces and abstract classes, which will be mentioned in the following specific design.
  2. Liskov Substitution Principle: the Liskov Substitution Principle is one of the basic principles of object-oriented design. The Richter substitution principle says that wherever a base class can appear, a subclass must appear. LSP is the cornerstone of inheritance reuse. Only when the derived class can replace the base class and the function of the software unit is not affected, the base class can be truly reused, and the derived class can also add new behavior on the basis of the base class. Richter's substitution principle is a supplement to the "open close" principle. The key step in realizing the "open close" principle is abstraction. The inheritance relationship between base class and subclass is the concrete realization of abstraction, so the Richter substitution principle is the specification of the specific steps of realizing abstraction.
  3. Dependency Inversion Principle: This is the basis of the opening and closing principle. Specific content: for interface programming, it depends on abstraction rather than concrete implementation.
  4. Interface aggregation principle: this principle means that using multiple isolated interfaces is better than using a single interface. It also means to reduce the coupling between classes. From here, we can see that in fact, the design pattern is a software design idea, starting from the large-scale software architecture for the convenience of upgrading and maintenance. Therefore, it appears many times above: reduce dependence and coupling.
  5. Demeter Principle: why is it called the least known principle? That is, an entity should interact with other entities as little as possible to make the system functional modules relatively independent.
  6. Composite Reuse Principle: the principle is to try to use composition / aggregation instead of inheritance.

3. What are the design patterns?

Creation mode: factory method mode, abstract factory mode, singleton mode, builder mode and prototype mode;
Structural mode: adapter mode, decoration mode, agent mode, appearance mode, bridge mode, combination mode and sharing mode;
Behavioral mode: policy mode, template method mode, observer mode, iterator mode, responsibility chain mode, command mode, memo mode, state mode, visitor mode, mediator mode and interpreter mode.

4. What is singleton mode?

In Java applications, only one instance of a class exists.

5. Where has singleton mode been used?

  1. Configuration files defined in the project;
  2. Servlet objects are singletons by default;
  3. Thread pool and database connection pool;
  4. Bean objects in Spring are singletons by default;
  5. Implement website counter;
  6. Jvm built-in cache framework (define single instance HashMap);
  7. Define enumeration constant information;

6. What are the advantages and disadvantages of singleton mode?

Advantages: the heap can be accessed quickly and new objects can not be accessed frequently.
Disadvantages: when multiple threads access the same singleton object, there may be thread safety problems.

7. What are the ways to write the singleton mode?

  1. Lazy, thread unsafe: create the singleton object only when you really need to obtain the object. There is a thread problem in this writing method
1.package com.singleton;  
2.  
3.import java.io.Serializable;  
4.  
5./** 
6. * @ClassName Slovenly 
7. * @Description 1.Lazy: thread unsafe 
8. * @Author honey-Yuan Xiaokang 
9. * @Date 2020/6/10 22:06 
10. * @Version 1.0 
11. */  
12.public class Slovenly implements Serializable {  
13.  
14.    private static Slovenly slovenly = null;  
15.  
16.    /** 
17.     * Privatized constructor 
18.     */  
19.    private Slovenly() {  
20.  
21.    }  
22.  
23.    /** 
24.     * Lazy: the object is created only when it is really needed 
25.     */  
26.    public static Slovenly getInstance() {  
27.        if (slovenly == null) {  
28.            slovenly = new Slovenly();  
29.        }  
30.        return slovenly;  
31.    }  
}  
  1. Lazy, thread safe: this method can ensure thread safety, but it is very inefficient to obtain the singleton object
1.package com.singleton;  
2.  
3./** 
4. * @ClassName SlovenlyLock 
5. * @Description 2.Lock lazy: thread safe, inefficient 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 22:15 
8. * @Version 1.0 
9. */  
10.public class SlovenlyLock {  
11.  
12.    private static SlovenlyLock slovenlyLock;  
13.  
14.    private SlovenlyLock() {  
15.  
16.    }  
17.  
18.    public static synchronized SlovenlyLock getInstance() {  
19.        if (slovenlyLock == null) {  
20.            slovenlyLock = new SlovenlyLock();  
21.        }  
22.        return slovenlyLock;  
23.    }  
}  
  1. Lazy double check lock: it can ensure thread safety. It will only lock when creating the singleton object, and will not lock when acquiring the singleton object. It is more efficient.
1.package com.singleton;  
2.  
3./** 
4. * @ClassName DoubleInspectionLock 
5. * @Description 3.Double check lock: thread safety and high efficiency 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 22:22 
8. * @Version 1.0 
9. */  
10.public class DoubleInspectionLock {  
11.  
12.    private static DoubleInspectionLock doubleInspectionLock;  
13.  
14.    private DoubleInspectionLock() {  
15.  
16.    }  
17.  
18.    public static DoubleInspectionLock getInstance() {  
19.        if (doubleInspectionLock == null) {  
20.            synchronized (DoubleInspectionLock.class) {  
21.                if (doubleInspectionLock == null) {  
22.                    doubleInspectionLock = new DoubleInspectionLock();  
23.                }  
24.            }  
25.        }  
26.        return doubleInspectionLock;  
27.    }  
}  
  1. Hungry Chinese style: create the object when the class file is loaded, which is inherently thread safe and wastes memory space
1.package com.singleton;  
2.  
3./** 
4. * @ClassName Hungry 
5. * @Description Hungry man style: congenital thread safety, wasting memory space 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 22:34 
8. * @Version 1.0 
9. */  
10.public class Hungry {  
11.  
12.    /** 
13.     * The object is created when the class file is loaded 
14.     */  
15.    private Hungry() {  
16.  
17.    }  
18.  
19.    private static Hungry hungry = new Hungry();  
20.  
21.    public static Hungry getInstance() {  
22.        return hungry;  
23.    }  
}  
  1. Hungry Han formula (constant)
1.package com.singleton;  
2.  
3./** 
4. * @ClassName HungryConstant 
5. * @Description 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 22:39 
8. * @Version 1.0 
9. */  
10.public class HungryConstant {  
11.  
12.    private HungryConstant() {  
13.  
14.    }  
15.  
16.    public static final HungryConstant HUNGRYCONSTANT = new HungryConstant();  
17.  
}  
  1. Static code block
1.package com.singleton;  
2.  
3./** 
4. * @ClassName StaticCodeBlock 
5. * @Description Static code block 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 22:45 
8. * @Version 1.0 
9. */  
10.public class StaticCodeBlock {  
11.  
12.    private StaticCodeBlock() {  
13.  
14.    }  
15.  
16.    private static StaticCodeBlock staticCodeBlock;  
17.  
18.    static {  
19.        staticCodeBlock = new StaticCodeBlock();  
20.    }  
21.  
22.    public static StaticCodeBlock getInstance() {  
23.        return staticCodeBlock;  
24.    }  
25.}  
  1. Static internal class: it combines the respective advantages of lazy and hungry. It can only be loaded when the object is really needed. The loaded class is thread safe
1.package com.singleton;  
2.  
3./** 
4. * @ClassName StaticInnerClass 
5. * @Description Static inner class 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 23:50 
8. * @Version 1.0 
9. */  
10.public class StaticInnerClass {  
11.  
12.    private StaticInnerClass() {  
13.  
14.    }  
15.  
16.    private static class SingletonHolder {  
17.        private static final StaticInnerClass STATIC_INNER_CLASS = new StaticInnerClass();  
18.    }  
19.  
20.    public static StaticInnerClass getInstance() {  
21.        return SingletonHolder.STATIC_INNER_CLASS;  
22.    }  
23.}  
  1. Enumeration: enumeration is the safest and cannot be cracked by reflection and serialization
1.package com.singleton;  
2.  
3./** 
4. * @ClassName Enum 
5. * @Description 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 23:45 
8. * @Version 1.0 
9. */  
10.public enum Enum {  
11.  
12.    /** 
13.     * Enumeration singleton 
14.     */  
15.    INSTANCE;  
16.  
17.    public void getInstance() {  
18.        System.out.println("getInstance");  
19.    }  
}  

8. How many ways to create objects?

  1. Direct new object;
  2. Using cloned objects;
  3. Create objects using reflections;
  4. Serialization and deserialization;

9. What are the ways to crack single cases?

The singleton can be cracked using reflection and serialization.

10. How to use reflection to crack single cases?

1.try {  
2.            Class<?> aClass = Class.forName("com.crack.PreventCracking");  
3.            Constructor<?> constructor = aClass.getDeclaredConstructor();  
4.            constructor.setAccessible(true);  
5.            PreventCracking preventCracking2 = (PreventCracking) constructor.newInstance();  
6.            PreventCracking preventCracking1 = PreventCracking.getInstance();  
7.            System.out.println(preventCracking1 == preventCracking2);  
8.        } catch (Exception e) {  
9.            e.printStackTrace();  
10.        }  

11. How to prevent reflection cracking?

1.package com.crack;  
2.  
3./** 
4. * @ClassName PreventCracking 
5. * @Description Anti reflection cracking single example 
6. * @Author honey-Yuan Xiaokang 
7. * @Date 2020/6/10 23:08 
8. * @Version 1.0 
9. */  
10.public class PreventCracking {  
11.  
12.    private static PreventCracking preventCracking = null;  
13.  
14.    private PreventCracking() throws Exception {  
15.        if (preventCracking != null) {  
16.            throw new Exception("This object has been created, please do not create it again!");  
17.        } else {  
18.            preventCracking = this;  
19.        }  
20.    }  
21.  
22.    public static PreventCracking getInstance() throws Exception {  
23.        if (preventCracking == null) {  
24.            preventCracking = new PreventCracking();  
25.        }  
26.        return preventCracking;  
27.    }  
28.}  

12. How to use serialization to crack a singleton?

1.// Use serialization to crack the singleton  
2.        FileOutputStream fos = null;  
3.        ObjectOutputStream oos = null;  
4.        ObjectInputStream ois = null;  
5.        try {  
6.            // 1. Serialize the object and store it in the local file  
7.            fos = new FileOutputStream("d:/code/slovenly.txt");  
8.            oos = new ObjectOutputStream(fos);  
9.            Slovenly slovenly1 = Slovenly.getInstance();  
10.            oos.writeObject(slovenly1);  
11.            //2. Deserialize objects from hard disk to memory  
12.            ois = new ObjectInputStream(new FileInputStream("d:/code/slovenly.txt"));  
13.            Slovenly slovenly2 = (Slovenly) ois.readObject();  
14.            System.out.println(slovenly1 == slovenly2);  
15.        } catch (Exception e) {  
16.            e.printStackTrace();  
17.        } finally {  
18.            try {  
19.                if (ois != null) {  
20.                    ois.close();  
21.                }  
22.                if (oos != null) {  
23.                    oos.close();  
24.                }  
25.                if (fos != null) {  
26.                    fos.close();  
27.                }  
28.            } catch (IOException e) {  
29.                e.printStackTrace();  
30.            }  
31.        }  

13. How to prevent serialization cracking of singletons?

1.package com.singleton;  
2.  
3.import java.io.Serializable;  
4.  
5./** 
6. * @ClassName Slovenly 
7. * @Description 1.Lazy: thread unsafe 
8. * @Author honey-Yuan Xiaokang 
9. * @Date 2020/6/10 22:06 
10. * @Version 1.0 
11. */  
12.public class Slovenly implements Serializable {  
13.  
14.    private static Slovenly slovenly = null;  
15.  
16.    /** 
17.     * Privatized constructor 
18.     */  
19.    private Slovenly() {  
20.  
21.    }  
22.  
23.    /** 
24.     * Lazy: the object is created only when it is really needed 
25.     */  
26.    public static Slovenly getInstance() {  
27.        if (slovenly == null) {  
28.            slovenly = new Slovenly();  
29.        }  
30.        return slovenly;  
31.    }  
32.  
33.    /** 
34.     * Serialization production callback method, through which the production singleton object is deserialized 
35.     * 
36.     * @return Object 
37.     */  
38.    public Object readResolve() {  
39.        return slovenly;  
40.    }  
41.}  

14. What is the factory model?

The factory pattern provides the best way to create objects. In factory mode, when creating objects, the creation logic is not exposed to the client, and a common interface is used to point to the newly created objects. It realizes the separation of creator and caller. The factory mode is divided into simple factory, factory method, abstract factory and static factory.

15. Where has the factory model been used?

Spring IOC uses BeanFactory when creating beans.

16. What are the advantages and disadvantages of the factory model?

Advantages: simple code structure; The process of obtaining products is simpler; It meets the opening and closing principle, that is, it is open to expansion and closed to modification; Reduce the coupling of programs; Reduce duplicate redundant codes; Reduces errors caused by user creation logic.
Disadvantages: the expansion is cumbersome. During the expansion, the abstract factory and factory implementation class need to be changed at the same time.

17. What is the agency model?

The proxy mode mainly enhances the implementation before and after method execution.

18. Where has the agent model been used?

  1. Log collection
  2. Permission control
  3. Implement aop
  4. Mybatis mapper
  5. Spring transactions
  6. Global catch exception
  7. Rpc remote call interface
  8. Proxy data source

19. Talk about the implementation principle of agent mode?

The proxy mode mainly includes three roles: abstract subject role, delegate role and proxy role, as shown in the following figure:

Abstract topic role: it can be an interface or an abstract class;
Delegate role: real subject role, the specific executor of business logic;
Proxy role: it contains a reference to the real object RealSubject, which is responsible for calling the real subject role, and pre-processing and post-processing before and after the real subject role processing.

20. What are the agency modes?

The agent mode is divided into static agent mode and dynamic agent mode; Dynamic agent mode is divided into JDK dynamic agent and Cglib dynamic agent.

21. What is the static proxy model?

The programmer creates or tools generate the source code of the agent class, and then compiles the agent class. The so-called static means that the bytecode file of the agent class already exists before the program runs, and the relationship between the agent class and the delegate class is determined before the program runs.

22. How to implement static proxy mode based on Interface?

23. How to implement static proxy mode based on inheritance?

24. What is the difference between dynamic agent and static agent?

Dynamic proxy does not need to write proxy class objects, which are generated automatically by the program, while static proxy requires us to write proxy class objects ourselves.

25. What is the dynamic agent model?

The dynamic agent does not care about the agent class in the implementation phase, but specifies which object in the run-time phase.
The source code of dynamic proxy class is dynamically generated by JVM according to reflection and other mechanisms during program operation.

26. How to implement JDK dynamic agent?

  1. Create the proxy interface and class;
  2. Implement the InvocationHandler interface to handle all methods declared in the target interface in a unified manner;
  3. Call the static method of Proxy, create Proxy class and generate corresponding Proxy object;

27. Talk about the implementation principle of JDK dynamic agent?

Using the interceptor mechanism, the invoke method in the InvocationHandler interface must be implemented to enhance the target method.

28. Talk about the idea of handwritten JDK dynamic agent?

  1. Create InvocationHandler interface and define an invoke method;
  2. Use java reflection technology to obtain all methods under the interface and splice $proxy0 Java code;
  3. Add $proxy0 Java is compiled into a class file and read into memory;

29. Talk about the implementation principle of CGLIB dynamic agent?

Use ASM bytecode technology to generate subclasses to enhance the target method.
Cglib relies on ASM bytecode technology to directly generate class files, and then use class loader to read them into the program;
Using fastclass to index the methods of the proxy class does not need to rely on reflection to find the target method, so the efficiency is higher than that of Jdk dynamic proxy.

30. What is the difference between JDK dynamic agent and CGLIB dynamic agent?

  1. Jdk dynamic proxy uses reflection technology to generate anonymous proxy classes, and adopts InvokeHandler callback method to realize enhancement. At the same time, it is also an interface based way to realize proxy;
  2. Cglib dynamic proxy uses asm bytecode technology to generate a subclass to cover it, and uses fastClass mechanism to index the whole proxy class, which is more efficient than reflection;
  3. In Spring, if the object to be proxied implements the interface, it adopts Jdk dynamic proxy, and if it does not implement the interface, it uses Cglib dynamic proxy.

31. Why does @ async annotation fail?

When using @ Async annotation, you should use a separate class to call.

  1. If the @ Async annotation is used on the interface implemented by the control class, the JDK dynamic proxy will be used at the bottom of the code, which will cause the control class to be unable to be injected into the spring MVC container. The page will report 404 and the interface cannot be found.
  2. If you call the @Async in the same class with the method of annotation, the @Async will not have the effect of asynchronism. Although the code is at the bottom of the CGLIB dynamic proxy, it can be registered in the SpringMVC container, but the two methods in the same class will cause the @Async annotation to go without the proxy class, and can not enhance the method.
  3. If the @ EnableAsync annotation is not used, the @ Async annotation will also be invalidated.

32. Why is the @ transaction annotation invalid?

When using the @ Transaction annotation, a separate class should be called.

  1. If you call the @Transaction annotation in the same class, the annotation will fail.
  2. If you use the try catch statement in the method, Aop will not catch the exception, and the code will not be rolled back. You need to roll back manually.

33. How to dynamically proxy @ Async and @ Transaction based on JDK?

34. How to write @ Async and @ Transaction based on AOP?

35. What is decoration mode?

Add additional functions without changing the original code.

(1) Abstract component: define an abstract interface to standardize the classes that prepare additional functions
(2) Concrete component: the class to be added with functions, which implements the abstract component role interface
(3) Abstract decorator: holds references to specific component roles and defines interfaces consistent with abstract component roles
(4) Concrete decoration: realize the role of abstract decorator and be responsible for adding additional functions to specific components.

36. Where have decorative patterns been used?

Multi level cache design; First level and second level cache in mybatis; IO stream.

37. How to realize multi-level cache based on decoration mode?

38. What is the observer model?

When the state of an object changes, it is notified to all other objects.

39. Where has the observer model been used?

Zk event monitoring; The distributed configuration center refreshes the configuration file; Send messages from different channels in the business.

40. How to implement asynchronous multi-channel group sending framework based on observer mode?

41. What is the responsibility chain model?

Definition: multiple objects have the opportunity to process the request, thus avoiding the coupling relationship between the sender and receiver of the request. Connect these objects into a chain and pass the request along the chain until an object processes it. Its procedure is actually a recursive call.

  1. Abstract handler role: defines an interface to handle requests. If necessary, the interface can define a method to set and return a reference to the next home. This role is usually implemented by a Java abstract class or Java interface.
  2. Concrete handler role: after receiving the request, the specific handler can choose to dispose of the request or send the request to the next home. For the specific visitor, you can handle the next home if you need to.

42. What are the advantages and disadvantages of the responsibility chain model?

advantage:
The main function of the responsibility chain model is: dynamic combination, decoupling between requestor and receiver.
The requestor and the receiver are loosely coupled: the requestor does not need to know the receiver or how to handle it. Each responsibility object is only responsible for its own scope of responsibility, and the rest is handed over to the successor. The components are completely decoupled.
Dynamic combination of responsibilities: the responsibility chain mode will disperse the functions into separate responsibility objects, and then dynamically combine them to form a chain when in use, so that the responsibility objects can be allocated flexibly, and the responsibilities of objects can be added and changed flexibly.

Disadvantages:
Many fine-grained objects are generated: because the function processing is scattered into separate responsibility objects, each object has a single function. To process the whole process, many responsibility objects are required, and a large number of fine-grained responsibility objects will be generated.
Not necessarily able to handle: each responsibility object is only responsible for its own part, so there may be a request. Even if the whole chain is completed, no responsibility object will handle it. This requires providing default processing and paying attention to the effectiveness of the construction chain.

43. Where has the responsibility chain model been used?

  1. Multi condition process judgment and permission control;
  2. ERP system process approval: general manager, personnel manager and project manager;
  3. Risk control system: dishonest list → whether the credit card is overdue → ant credit score 650;
  4. In Java Filter, when the client sends a request to the server, it will go through parameter filtering, session filtering, form filtering, hidden filtering and detection request header filtering;
    Gateway permission control: Api interface current limiting → blacklist interception → user session verification → parameter filtering.

44. How to implement the enterprise gateway system based on the responsibility chain model?

45. What is the strategic model?

The strategy mode is the packaging of the algorithm. It separates the responsibility of using the algorithm from the algorithm itself and delegates it to different objects for management. Finally, it can solve the problem of multiple if judgments.

  1. Context role: holds a reference to Strategy.
  2. Abstract strategy role: This is an abstract role, usually implemented by an interface or abstract class. This role gives the interfaces required for all specific policy classes.
  3. Concrete strategy role: encapsulates relevant algorithms or behaviors.

Define policy interface - > implement different policy classes - > call policies using polymorphism or other methods

46. Where has the strategic model been used?

  1. Send SMS asynchronously, such as Alibaba cloud, Tencent cloud and other SMS channels;
  2. Aggregated payment system, UnionPay payment, Alipay, WeChat payment, etc.
  3. Joint landing QQ, nailing, wechat joint landing channels, etc;

47. How to implement multi-channel messaging platform based on policy mode?

48. What is the template method pattern?

  1. Define a skeleton with common behavior, and complete the implementation of some steps in subclasses.
  2. Template method pattern is one of the most common patterns among all patterns. It is a basic technology of code reuse based on inheritance, and has no correlation. Therefore, in the template method pattern, there are only inheritance relationships.

Key points of core design:
AbstractClass: abstract class that defines and implements a template method. This template method defines the skeleton of the algorithm, and the composition steps of logic are postponed to subclasses in the corresponding abstract operations.
ConcreteClass: implementation class, which implements one or more abstract methods defined by the parent class.

49. What is appearance mode?

Facade: it hides the complexity of the system and provides an interface for the client to access the system. This type of design pattern belongs to structural pattern. It provides a unified access interface for a group of interfaces in the subsystem, which makes the subsystem easier to access or use.

In short, this mode encapsulates some complex processes into an interface for external users to use more simply. In this mode, three roles are designed.
1) Facade role: the core of appearance mode. It is called by the customer role, and it is familiar with the functions of the subsystem. According to the needs of the customer's role, several combinations of functions are reserved internally.
2) Subsystem role: it realizes the functions of the subsystem. It is unknown to the customer role and Facade. It can interact with each other within the system, or it can be called by the interface for the outside world.
3) Customer role: complete the function to be realized by calling Facede.

50. What is state mode?

State mode allows an object to change its behavior when its internal state changes. This object looks like it has changed its class.

Topics: Java Design Pattern mr