Explanation of 23 design patterns in JAVA

The 23 design patterns of JAVA are explained as follows:

 

 

1. Definition of Singleton Pattern
: Ensure a class has only one instance, and provide a global point of access to it.
Generic code: (is thread safe)

public class Singleton {
 private static final Singleton singleton = new Singleton();
//限制产生多个对象
 private Singleton(){
 }
 //通过该方法获得实例对象
 public static Singleton getSingleton(){
 return singleton;
 } 
 //类中其他方法,尽量是 static
 public static void doSomething(){
 } }

Usage scenarios:
● An environment that requires the generation of a unique serial number;
● A shared access point or shared data is required in the entire project, such as a counter on a Web page, so you don’t need to record every refresh in the database, and use the singleton mode Keep the value of the counter and ensure thread safety;
● Create an object that consumes too many resources, such as accessing resources such as IO and database;
● Need to define a large number of static constants and static methods (such as tool classes) in the environment, Singleton mode can be adopted (of course, it can also be directly declared as static).

Thread unsafe example:

public class Singleton {
 private static Singleton singleton = null;
 //限制产生多个对象
 private Singleton(){
 } 
 //通过该方法获得实例对象
 public static Singleton getSingleton(){
 if(singleton == null){
 singleton = new Singleton();
 }
 return singleton;
 } }

Solution:
Add the synchronized keyword before the getSingleton method, or add synchronized in the getSingleton method to achieve. The optimal approach is to write it as generic code.

2. Factory mode
Definition: Define an interface for creating an object, but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses
. A class. The factory method delays the instantiation of a class to its subclasses.)
Product is responsible for defining the commonality of products for abstract product classes, and realizes the most abstract definition of things;
Creator creates classes for abstraction, that is, abstract factories. The creation of product classes is done by the concrete implementation factory ConcreteCreator.
Specific factory class code:

public class ConcreteCreator extends Creator {
public <T extends Product> T createProduct(Class<T> c){
 Product product=null;
 try {
 product =
(Product)Class.forName(c.getName()).newInstance();
 } catch (Exception e) {
 //异常处理
 }
 return (T)product; 
 } }

Simple factory mode:
a module only needs one factory class, there is no need to generate it, use static methods Multiple factory classes:
each race (specific product class) corresponds to a creator, and each creator is responsible independently Create the corresponding product object, which is very consistent with the single responsibility principle instead of the singleton pattern: the
core requirement of the singleton pattern is that there is only one object in memory, and only one object can be produced in memory through the factory method mode
Lazy initialization:
ProductFactory is responsible for the product class Object creation work, and generate a cache through the prMap variable, which is reserved for objects that need to be reused again Usage
scenarios: jdbc connects to the database, hardware access, reduces object generation and destruction

3. Abstract Factory Pattern
Definition: Provide an interface for creating families of related or dependent objects
without specifying their concrete classes. (Provide an interface for creating a group of related or interdependent objects without specifying their specific kind.)

Abstract factory class code:


public abstract class AbstractCreator {
 //创建 A 产品家族
 public abstract AbstractProductA createProductA();
 //创建 B 产品家族
 public abstract AbstractProductB createProductB();
}

Usage scenario:
A family of objects (or a group of objects without any relationship) all have the same constraints.
When it comes to different operating systems, you can consider using the abstract factory pattern.

4. Template Method Pattern Definition
: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.Template Method lets subclasses redefine certain steps of an
algorithm without changing the algorithm's structure. The framework of the algorithm, and some steps are delayed to the subclass. So that the subclass can redefine
some specific steps of the algorithm without changing the structure of the algorithm.)
AbstractClass is called an abstract template, and its methods are divided into two categories:
● Basic methods
Basic methods, also called basic operations, are methods implemented by subclasses and called in template methods.
● Template method
There can be one or several methods. Generally, it is a specific method, that is, a framework, which implements the scheduling of basic methods and completes the fixed logic.
Note: In order to prevent malicious operations, general template methods are added with the final keyword and are not allowed to be overwritten.
Concrete templates: ConcreteClass1 and ConcreteClass2 belong to concrete templates, which implement one or more abstract methods defined by the parent class, that is, the basic methods defined by the parent class can be implemented in subclasses. Scenarios: ● Multiple subclasses have public methods
,
and When the logic is basically the same.
● For important and complex algorithms, the core algorithm can be designed as a template method, and the relevant detailed functions around it can be realized by each subclass.
● When refactoring, the template method pattern is a frequently used pattern, which extracts the same code into the parent class, and then constrains its behavior through the hook function (see "Extension of the template method pattern").

5. Definition of Builder Pattern
: Separate the construction of a complex object from its representation so that the same construction process can create different representations. (Separate the construction of a complex object from its representation so that the same construction process Different representations can be created.)
● Product product class
usually implements the template method pattern, that is, there are template methods and basic methods. BenzModel and BMWModel in the example belong to the product class.
● Builder Abstract builder
The construction of standardized products is generally realized by subclasses. The CarBuilder in the example belongs to the abstract builder.
● ConcreteBuilder
implements all the methods defined by the abstract class and returns a constructed object. BenzBuilder and BMWBuilder in the example belong to concrete builders.
● Director The director class
is responsible for arranging the order of existing modules, and then tells the Builder to start construction.
Use scenarios:
● When the same method, different execution order, and different event results are generated, the builder mode can be used.
● Multiple components or parts can be assembled into one object, but the running results produced are different, then this mode can be used.
● The product class is very complex, or the invocation sequence in the product class produces different effects, and it is very appropriate to use the builder pattern at this time.
The difference between the builder pattern and the factory pattern:
The main function of the builder pattern is the call sequence arrangement of the basic methods. These basic methods have been implemented, and the
objects generated in different orders are also different;
the factory method focuses on creation, and the creation of parts is its main responsibility, and the assembly sequence is not it. concerned about

6. Definition of Proxy Pattern
: Provide a surrogate or placeholder for another object to control access to it
. It can be an abstract class or an interface. It is the most common business type definition without special requirements. ● RealSubject Concrete subject role It is also called delegated role and delegated role. It is the one who is taken advantage of and is the specific executor of business logic. ● Proxy Proxy theme role It is also called delegate class and proxy class. It is responsible for the application of the real role, entrusts the implementation of all method restrictions defined by the abstract theme class to the real theme role, and does preprocessing and post-processing work before and after the real theme role is processed. Ordinary proxy and mandatory proxy: Normal proxy means that we need to know the existence of the proxy, that is, the existence of the similar GamePlayerProxy class, before we can access it; mandatory proxy means that the caller directly calls the real character without caring whether the proxy exists, its proxy The generation of is determined by real characters. Ordinary proxy: In this mode, the caller only knows the proxy and does not need to know who the real role is, which shields the impact of the change of the real role on the high-level modules, and can modify the real theme role as he wants. There is no impact, as long as you implement the method corresponding to the interface, this mode is very suitable for occasions that require high scalability. Force proxy:













The concept of enforcing proxy is to look up the proxy role from the real role, not allowing direct access to the real role. The high-level module can access all the methods of the real role as long as it calls getProxy. It does not need to generate a proxy at all, and the management of the proxy has been completed by the real role itself.
Dynamic proxy:
Generate all methods according to the interface being proxied, that is to say, given an interface, the dynamic proxy will declare "I have implemented all the methods under this interface".
Two lines of independent development. The dynamic proxy realizes the responsibility of the proxy, and the business logic Subject realizes the relevant logic functions, and there is no necessary mutual coupling relationship between the two. Notify Advice to cut in from another aspect,
and finally couple in the high-level module, that is, Client, to complete the logic encapsulation task.
Schematic diagram of the dynamic proxy calling process:
the intention of the dynamic proxy: cross-section programming, to enhance or control the behavior of the object without changing the structure of our existing code.
First condition: The proxied class must implement an interface.

7. Prototype Pattern
definition: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype
. .)
Prototype mode general code:


public class PrototypeClass implements Cloneable{
 //覆写父类 Object 方法
 @Override
 public PrototypeClass clone(){
 PrototypeClass prototypeClass = null;
 try {
 prototypeClass = (PrototypeClass)super.clone();
 } catch (CloneNotSupportedException e) {
 //异常处理
 }
 return prototypeClass;
 } }

The prototype mode is actually to implement the Cloneable interface and rewrite the clone () method.
Advantages of using the prototype mode:
● Good performance
The prototype mode is a copy of the memory binary stream, which is much better than directly newing an object, especially when a large number of objects are to be generated in a loop body, the prototype mode can better reflect its advantage.
● Evasion of the constraint of the constructor
This is its advantage and disadvantage, copy directly in the memory, the constructor will not be executed (see Section 13.4).
Usage scenarios:
● Resource optimization scenario
Class initialization needs to consume a lot of resources, including data and hardware resources.
● Scenarios with performance and security requirements
Creating an object through new requires very cumbersome data preparation or access rights, so the prototype mode can be used.
● Scenarios where one object has multiple modifiers
When an object needs to be accessed by other objects, and each caller may need to modify its value, you can consider using the prototype mode to copy multiple objects for the caller to use.
Shallow copy and deep copy:
Shallow copy: The method clone provided by the Object class just copies the object, and the arrays and reference objects inside the object are not copied, but still point to the internal element address of the original object. This kind of copy is called shallow copy. Other primitive types such as int, long, char, string (as primitive types), etc. will be copied.
Note: When using the prototype mode, the referenced member variable must meet two conditions before it will be copied: one is the member variable of the class, not the variable in the method; the other is that it must be a mutable reference object, not a primitive type or an immutable object.
Deep copy: make independent copies of private class variables
如:thing.arrayList = (ArrayList)this.arrayList.clone();

8. Mediator mode
Definition: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other
explicitly, and it lets you vary their interaction independently. (Use a mediator object to encapsulate a series of object interaction, the mediator makes the objects do not need to interact with each other explicitly, so that the coupling is loose, and the interaction between them can be changed independently.) ● Mediator abstract mediator role The abstract mediator
role
defines a unified interface, using Communication between colleagues roles.
● Concrete Mediator Concrete mediator role
realizes collaborative behavior by coordinating various co-worker roles, so it must depend on each co-worker role.
● Colleague role
Every colleague knows the mediator role, and when communicating with other colleagues, it must cooperate through the mediator role. The behavior of each colleague class is divided into two types: one is the behavior of the colleague itself, such as changing the state of the object itself, handling its own behavior, etc. There is no dependency; the second is the behavior that must rely on the intermediary to complete, called the dependent method (Dep-Method).
Generic abstract mediator code:

public abstract class Mediator {
 //定义同事类
 protected ConcreteColleague1 c1;
 protected ConcreteColleague2 c2;
 //通过 getter/setter 方法把同事类注入进来
 public ConcreteColleague1 getC1() {
 return c1;
 }
 public void setC1(ConcreteColleague1 c1) {
 this.c1 = c1;
 }
 public ConcreteColleague2 getC2() {
 return c2;
}
 public void setC2(ConcreteColleague2 c2) {
 this.c2 = c2;
 }
 //中介者模式的业务逻辑
 public abstract void doSomething1();
 public abstract void doSomething2();
}

ps: The reason for using colleague class injection instead of abstract injection is because the abstract class does not have the methods that every colleague class must complete. That is, the methods in each colleague class are different.
Question: Why should the colleague class use the constructor to inject the mediator, and the mediator uses the getter/setter method to inject the colleague class?
This is because the colleague class must have a mediator, but the mediator can only have part of the colleague class.
Usage scenario:
The intermediary pattern is suitable for tight coupling between multiple objects. The standard of tight coupling is: a spider web structure appears in the class diagram, that is, each class has a direct relationship with other classes.

9. Command mode
Definition: Encapsulate a request as an object, thereby letting you parameterize clients with different
requests, queue or log requests, and support undoable operations.
Terminal parameterization, queuing requests or recording request logs, can provide command undo and restore functions.)
● Receive receiver role
This role is the role of work, the command passed here should be executed, specific to our above In the example, there are three implementation classes of Group (requirements group, art group, code group).
● Command role
All commands to be executed are declared here.
● Invoker Invoker role
Receives and executes commands. In the example, I (the project manager) is in this role.
Usage scenario:
The command mode can be used where it is considered to be a command. For example, in GUI development, the click of a button is a command, and the command mode can be used; when simulating a DOS command, of course the command mode should also be used; trigger-feedback Mechanism handling etc.

10. Responsibility Chain Mode
Definition: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass
the request along the chain until an object handles it. Objects have the opportunity to process the request, thereby avoiding the coupling relationship between the sender and receiver of the request.Connect these objects into a chain, and pass the
request along this chain until an object handles it.)
Abstraction Handler's code:


public abstract class Handler {
 private Handler nextHandler;
 //每个处理者都必须对请求做出处理
 public final Response handleMessage(Request request){
 Response response = null; 
 //判断是否是自己的处理级别

if(this.getHandlerLevel().equals(request.getRequestLevel())){
 response = this.echo(request);
 }else{ //不属于自己的处理级别
 //判断是否有下一个处理者
 if(this.nextHandler != null){
 response =
this.nextHandler.handleMessage(request);
 }else{
 //没有适当的处理者,业务自行处理
 }
 }
 return response;
 }
 //设置下一个处理者是谁
 public void setNext(Handler _handler){
 this.nextHandler = _handler;
 }
 //每个处理者都有一个处理级别
 protected abstract Level getHandlerLevel();
 //每个处理者都必须实现处理任务
 protected abstract Response echo(Request request);
}

The abstract processor implements three responsibilities:
one is to define a request processing method handleMessage, the only method open to the outside world; the
other is to define a chain arrangement method setNext to set the
next processor ; There are two ways to implement: define the level getHandlerLevel that you can handle
and echo the specific processing task.
Note:
The number of nodes in the chain needs to be controlled to avoid the situation of super long chains. The general method is to set a maximum number of nodes in the Handler, and judge whether it has exceeded its threshold in the setNext method. If it exceeds, the chain is not allowed to be established , to avoid unintentionally disrupting system performance.

11. Decorator Pattern
Definition: Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for
extending functionality. (dynamically add some additional responsibilities to an object. In terms of adding functionality , the decoration mode is more flexible than generating subclasses.)
● Component abstract component
Component is an interface or an abstract class, which defines our core object, that is, the most primitive object, such as the transcript above.
Note: In the decoration mode, there must be a most basic, core, and original interface or abstract class as the abstract
component of Component.
● ConcreteComponent The concrete component
ConcreteComponent is the core, the most original, the most basic implementation of the interface or abstract class, and it is what you want to decorate.
● Decorator Decorator
is generally an abstract class, what is it used for? To implement an interface or an abstract method, there may not necessarily be an abstract method in it, and there must be a private variable pointing to the Component abstract component in its properties.
● The specific decoration roles
ConcreteDecoratorA and ConcreteDecoratorB are two specific decoration classes. You need to decorate your core, most primitive and basic things into other things. The above example is to decorate a mediocre report card as a
parent Recognized transcripts.
Usage scenarios:
● Need to extend the function of a class, or add additional functions to a class.
● It is necessary to dynamically add functions to an object, and these functions can be revoked dynamically.
● It is necessary to modify or add functions for a batch of siblings, of course, it is the first choice for decoration mode.

12. Strategy Pattern
Definition: Define a family of algorithms, encapsulate each one, and make them
interchangeable. (Define a set of algorithms, encapsulate each algorithm, and make them interchangeable.)
● Context encapsulation role
It is also called context role, which acts as a link between the preceding and the following encapsulation, shielding high-level modules from direct access to policies and algorithms, and encapsulating possible changes.
● Strategy abstract strategy role
The abstraction of strategies and algorithm families, usually an interface, defines the methods and attributes that each strategy or algorithm must have. Readers may ask, what is the meaning of AlgorithmInterface in the class diagram, hey,
algorithm means "algorithm", and the meaning will be understood when combined.
● ConcreteStrategy Concrete strategy roles (multiple)
implement the operations in the abstract strategy, and this class contains specific algorithms.
Usage scenarios:
● Scenarios where multiple classes differ only slightly in algorithm or behavior.
● The scene where the algorithm needs to be switched freely.
● Scenarios where algorithmic rules need to be shielded.
Note: If the number of specific strategies exceeds 4, you need to consider using mixed mode
Strategy mode extension: strategy enumeration


public enum Calculator {
 //加法运算
 ADD("+"){
 public int exec(int a,int b){
 return a+b;
 }
 },
 //减法运算
 SUB("-"){
 public int exec(int a,int b){
 return a - b;
 }
 };
 String value = "";
 //定义成员值类型
 private Calculator(String _value){
 this.value = _value;
 }
 //获得枚举成员的值
 public String getValue(){
 return this.value;
 }
 //声明一个抽象函数
 public abstract int exec(int a,int b);
}

Definitions:
● It is an enumeration.
● It is a condensed enumeration of strategy patterns.
Note:
Restricted by the enumeration type, each enumeration item is public, final, and static, and the scalability is subject to certain constraints. Therefore, in system development, strategy enumeration generally plays a role that does not change frequently.
Fatal flaw: All strategies need to be exposed, and it is up to the client to decide which strategy to use.

13. Adapter Pattern
Definition: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces. (Transform the interface of a class into what the client expects Another interface to enable two classes to work together that would otherwise not work together due to mismatched interfaces.)
Class Adapter:
● Target Target role
This role defines what interface other classes are converted to, which is what we expect interface, the IUserInfo interface in the example is the target role.
● Adaptee source role
Who do you want to convert into the target role, this "who" is the source role, it is an existing class or object that works well, and after being packaged by the adapter role, it will become a brand new and beautiful role.
● Adapter role
The core role of the adapter pattern. The other two roles are existing roles, and the adapter role needs to be newly created. Its responsibility is very simple: how to convert the source role into the target role? Through inheritance or
class association.
Usage scenario:
When you are motivated to modify an interface that is already in production, the adapter pattern may be the most suitable pattern for you. For example, when the system is extended, an existing or newly created class needs to be used, but this class does not conform to the interface of the system, what should I do? Use the adapter pattern, which is also mentioned in our example.
Note:
Do not consider using the adapter mode in the detailed design stage, and use the main scenario for extended applications.
Object adapter:
The difference between an object adapter and a class adapter:
a class adapter is inheritance between classes, and an object adapter is a composite relationship of objects, which can also be said to be an association relationship of classes. This is the fundamental difference between the two. (There are relatively many scenes used by object adapters in actual projects).

14. Iterator Pattern
definition: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. (It provides a way to access the elements in a container
object without exposing the The internal details of the object.)
● Iterator abstract iterator
The abstract iterator is responsible for defining the interface for accessing and traversing elements, and basically has three fixed methods:
first() to get the first element, next() to access the next element , whether isDone() has visited the bottom
(Java is called hasNext() method).
● ConcreteIterator Concrete iterator
The concrete iterator role should implement the iterator interface to complete the traversal of container elements.
● Aggregate abstract container
The container role is responsible for providing an interface for creating a specific iterator role, and must provide a
method like createIterator(), which is generally iterator() method in Java.
● Concrete Aggregate Concrete container The
concrete container implements the method defined by the container interface and creates an object that holds the iterator.
ps: The iterator mode has been eliminated, and iterators have been applied to various collection classes (collections) in java. Using the iterator that comes with java has already met our needs.

15. Composite Pattern (Composite Pattern)
definition: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and
compositions of objects uniformly. "hierarchical structure, so that users have consistency in the use of single objects and composite objects.)
● Component abstract component role
defines the common methods and attributes of composite objects, and can define some default behaviors or attributes, such as getInfo in our example It is encapsulated in an abstract class.
● Leaf leaf component
Leaf object, there are no other branches under it, which is the smallest unit of traversal.
● Composite branch component
Branch object, its function is to combine branch nodes and leaf nodes to form a tree structure.
The general code of the branch component:
public class Composite extends Component { //component container private ArrayList componentArrayList = new ArrayList(); //add a leaf component or branch component public void add(Component component){ this.componentArrayList.add(component) ;






}
//Delete a leaf component or branch component
public void remove(Component component){ this.componentArrayList.remove(component); } //Get all leaf components and branch components under the branch public ArrayList getChildren(){ return this.componentArrayList ; } } Usage scenarios: ● Maintain and display part-whole relationship scenarios, such as tree menu, file and folder management. ● Scenarios in which some modules or functions can be isolated from a whole. Note: As long as it is a tree structure, consider using the composite mode.










16. Observer Pattern Definition
: Define a one-to-many dependency between objects so that when one object changes state, all its dependencies are notified and updated automatically. (Define
a one-to-many dependency between objects , so that whenever an object changes state, all objects that depend on it will be notified and automatically updated.)
● Subject Observer
Defines the responsibilities that the observer must implement, and it must be able to dynamically add and cancel observers. It is generally an abstract class or an implementation class, and it only completes the duties that must be realized as the observed: manage the observer and notify the observer
.
● Observer Observer
After receiving the message, the observer will perform the update (update method) operation to process the received information.
● ConcreteSubject The specific observer
defines the business logic of the observed object and defines which events are notified.
● ConcreteObserver Specific observers
Each observer reacts differently after receiving a message, and each observer has its own processing logic.
Observer general code:


public abstract class Subject {
 //定义一个观察者数组
 private Vector<Observer> obsVector = new Vector<Observer>();
 //增加一个观察者
 public void addObserver(Observer o){
 this.obsVector.add(o);
 }
 //删除一个观察者
 public void delObserver(Observer o){
 this.obsVector.remove(o);
 }
 //通知所有观察者
 public void notifyObservers(){
 for(Observer o:this.obsVector){
 o.update();
}
 } }

Usage scenarios:
● Associated behavior scenarios. It is important to note that association behaviors are divisible, not "composed" relationships.
● Event multi-level triggering scenarios.
● Cross-system message exchange scenarios, such as the processing mechanism of message queues.
Note:
● Problems with the broadcast chain
In an observer pattern, at most one object is both the observer and the observed, that is to say, the message is forwarded once (passed twice) at most.
● Asynchronous processing issues
There are many observers, and the processing time is relatively long. Asynchronous processing is used to consider the issues of thread safety and queues.

17. Facade Pattern
definition: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. (Requires that the communication between the outside of
a and its inside must Through a unified object. Facade mode provides a high-level interface, making the subsystem easier to use.)
● Facade role
The client can call the method of this role. This role is aware of all functions and responsibilities of the subsystem. Under normal circumstances, this role will delegate all the requests sent from the client to the corresponding subsystem, that is to say, this role has no actual business logic, but is just a delegation class.
● subsystem Subsystem role
There can be one or more subsystems at the same time. Each subsystem is not a single class, but a collection of classes. The subsystem is unaware of the existence of the facade. To the subsystem, the facade is just another client.
Use scenarios:
● Provide a complex module or subsystem with an interface for external access
● Subsystems are relatively independent—the external access to the subsystem only needs to be operated in a black box
● Prevent the spread of risks brought by low-level personnel
Note:
● A subsystem can have multiple facades
Facades do not participate in the business logic within the subsystem

18. Memento Pattern
definition: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later
. And save this state outside the object. In this way, the object can be restored to the original saved state later.) ● The
Originator role
records the internal state at the current moment, is responsible for defining which states belong to the backup range, and is responsible for creating and restoring memo
data.
● Memento role (simple javabean)
is responsible for storing the internal state of the Originator object and providing the internal state required by the originator when needed
.
● The Caretaker memento administrator role (a simple javabean)
manages, saves, and provides memos.
Use scenarios:
● Relevant state scenarios that need to save and restore data.
● Provide a rollback operation.
● In the replica scenario that needs to be monitored.
● The transaction management of the database connection is to use the memo mode.
Note:
●Lifetime of the memo
●Performance of the memo
Do not use the memo mode in scenarios where backups are created frequently (such as in a for loop).
Clone mode memo:
● The initiator role combines the initiator role and the memo role, and has dual functions.
Multi-state memo mode
● A BeanUtils class is added, in which backupProp converts all attribute values ​​of the initiator into HashMap, which is convenient for memo role storage. The restoreProp method is to return the value in the HashMap to the initiator role.
BeanUtil tool class code:

public class BeanUtils {
 //把 bean 的所有属性及数值放入到 Hashmap 中
 public static HashMap<String,Object> backupProp(Object bean){
 HashMap<String,Object> result = new
HashMap<String,Object>();
 try {
 //获得 Bean 描述
 BeanInfo
beanInfo=Introspector.getBeanInfo(bean.getClass());
 //获得属性描述
 PropertyDescriptor[]
descriptors=beanInfo.getPropertyDescriptors();
 //遍历所有属性
 for(PropertyDescriptor des:descriptors){
 //属性名称
 String fieldName = des.getName();
 //读取属性的方法
 Method getter = des.getReadMethod();
 //读取属性值
 Object fieldValue=getter.invoke(bean,new
Object[]{});
 if(!fieldName.equalsIgnoreCase("class")){
 result.put(fieldName, fieldValue);
 }
 }
 } catch (Exception e) {
 //异常处理
 }
 return result;
 }
 //把 HashMap 的值返回到 bean 中
 public static void restoreProp(Object bean,HashMap<String,Object>
propMap){
try {
 //获得 Bean 描述
 BeanInfo beanInfo =
Introspector.getBeanInfo(bean.getClass());
 //获得属性描述
 PropertyDescriptor[] descriptors =
beanInfo.getPropertyDescriptors();
 //遍历所有属性
 for(PropertyDescriptor des:descriptors){
 //属性名称
 String fieldName = des.getName();
 //如果有这个属性
 if(propMap.containsKey(fieldName)){
 //写属性的方法
 Method setter = des.getWriteMethod();
 setter.invoke(bean, new
Object[]{propMap.get(fieldName)});
 }
 }
 } catch (Exception e) {
 //异常处理
 System.out.println("shit");
 e.printStackTrace();
 }
 } }

Memo with multiple backups: Slightly better encapsulated: ensure that it can only be read by the originator
Create an empty interface IMemento—an interface with no method attributes, and then
create a built-in class in the originator class (also called A class within a class) Memento implements the IMemento interface and also implements its own business logic.

19. Definition of Visitor Pattern
: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the
elements on which it operates. It can define new operations on these elements without changing the data structure.) ● Visitor—abstract visitor abstract class or
interface
, which declares which elements the visitor can visit Specifically, in the program, the parameters of the visit method define which objects can be accessed.
● ConcreteVisitor——Specific visitor
It affects what a visitor should do and what to do after visiting a class.
● Element——abstract element
interface or abstract class, which declares which type of visitors to accept, and is defined programmatically through the parameters in the accept method.
● ConcreteElement—concrete element
implements the accept method, usually visitor.visit(this), and basically forms a pattern.
● ObjectStruture——Structure
object The element generator is generally accommodated in multiple containers of different classes and interfaces, such as List, Set, Map, etc. In projects, this role is rarely abstracted.
scenes to be used:
● An object structure contains many class objects with different interfaces, and you want to implement some operations on these objects that depend on their specific classes, that is to say, the situation where the iterator mode is no longer sufficient.
● Many different and unrelated operations need to be performed on the objects in an object structure, and you want to avoid these operations "polluting" the classes of these objects.

20. State mode (complex)
definition: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Its class.)
● State——abstract state role
Interface or abstract class, responsible for object state definition, and encapsulating environment role to realize state switching.
● ConcreteState—concrete state role
Each concrete state must complete two responsibilities: behavior management of the state and processing of the trend state. In layman's terms, it is the things to be done in the state and how the state transitions to other states.
● Context——environmental role
Defines the interface required by the client and is responsible for the switching of specific states.
Usage scenarios:
● Scenarios in which behavior changes with state changes
This is also the fundamental starting point of the state pattern, such as permission design. People in different states will have different results even if they perform the same behavior. In this case, you need to consider using the state pattern.
● A substitute for conditional and branch judgment statements
Note:
State mode is suitable for when an object changes in its state, its behavior also changes greatly, that is to say, when the behavior is constrained by the state You can use the state pattern, and when using it,
it is best not to have more than 5 states of the object.

21. Interpreter Pattern Definition
: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
(Given a language, define a grammar for its representation, and define an interpreter that uses the representation to interpret sentences in the language.)
● AbstractExpression——abstract interpreter
The specific interpretation tasks are completed by each implementation class, and the specific interpreters are respectively composed of TerminalExpression and
Non-terminalExpression Finish.
● TerminalExpression——terminal expression
implements the interpretation operation associated with the elements in the grammar. Usually, there is only one terminal expression in an interpreter mode, but there are multiple instances corresponding to different terminals. Specific to our example is the VarExpression
class, each terminal symbol in the expression generates a VarExpression object on the stack.
● NonterminalExpression——nonterminal symbol expression
Each rule in the grammar corresponds to a nonterminal expression. In our specific example, the rules of addition and subtraction correspond to the two classes AddExpression and SubExpression respectively. Non-terminal expressions
increase according to the complexity of the logic. In principle, each grammar rule corresponds to a non-terminal expression.
● Context—Environmental role
Specific to our example is to use HashMap instead.
Usage scenarios:
● Interpreter mode can be used for recurring problems
● A scenario where a simple syntax needs to be explained
Note:
Try not to use interpreter mode in important modules, otherwise maintenance will be a big problem. In the project, shell, JRuby, Groovy and other scripting languages ​​can be used instead of the interpreter mode to make up for the deficiency of Java compiled language.

22. Flyweight Pattern
definition: Use sharing to support large numbers of fine-grained objects efficiently.
(Using shared objects can effectively support a large number of fine-grained objects.)
Object information is divided into two parts: internal State (intrinsic) and external state (extrinsic).
● Internal state
The internal state is the information that can be shared by the object, which is stored inside the flyweight object and will not change with the environment.
● External state
The external state is a mark that the object can depend on. It is a state that changes with the environment and cannot be shared.
● Flyweight——Abstract Flyweight role
It is simply an abstract class of a product, and at the same time defines the interface or implementation of the external state and internal state of the object.
● ConcreteFlyweight——Concrete flyweight role
A specific product class that implements the business defined by abstract roles. What needs to be noted in this role is that the internal state processing should have nothing to do with the environment. An operation should not change the internal state while modifying the external state. This is absolutely not allowed.
● unsharedConcreteFlyweight—unshared flyweight role
An object that does not have external state or security requirements (such as thread safety) that cannot use sharing technology generally does not appear in the flyweight factory.
● FlyweightFactory——flyweight factory
The responsibility is very simple, that is, to construct a pool container and provide methods to obtain objects from the pool.
The code of flyweight factory:
public class FlyweightFactory {
//Define a pool container
private static HashMap pool= new
HashMap();
//Flyweight factory
public static Flyweight getFlyweight(String Extrinsic){ //The object that needs to be returned Flyweight flyweight = null; //There is no such object in the pool if (pool.containsKey(Extrinsic)){ flyweight = pool.get(Extrinsic); }else{ //Create a flyweight object according to the external state flyweight = new ConcreteFlyweight1(Extrinsic); //put it in the pool pool.put(Extrinsic, flyweight); } return flyweight; } } Usage scenarios: ● There are a large number of similar objects in the system. ● Fine-grained objects have relatively close external states, and the internal states have nothing to do with the environment, that is to say, objects have no specific identity. ● Scenarios that require a buffer pool. Note: ● Flyweight mode is not thread-safe, only rely on experience, consider thread safety where necessary, and do not need to consider it in most scenarios. There are as many flyweight objects in the object pool as possible, until enough is satisfied.



















● Performance safety: It is better to mark the external state with basic types of java, such as String and int, which can improve efficiency.

23. Definition of Bridge Pattern
: Decouple an abstraction from its implementation so that the two can vary independently
. The main responsibility is to define the behavior of the role, and at the same time save a reference to the realized role, which is usually an abstract class. ● Implementor——implementation role It is an interface or an abstract class that defines the necessary behaviors and attributes of a role. ● RefinedAbstraction——Refined abstraction role It refers to the realization role to revise the abstraction role. ● ConcreteImplementor——Concrete implementation role It implements the methods and properties defined by the interface or abstract class. Scenarios for use: ● Scenarios where inheritance is not expected or not applicable ● Scenarios where interfaces or abstract classes are unstable ● Scenarios that require high reusability Note: When you find that there are N layers of class inheritance, you can consider using the bridge mode. The bridge pattern mainly considers how to split abstraction and implementation. Design principles: Single Responsibility Principle: Single Responsibility Principle What are the benefits of the Single Responsibility Principle:

















● The complexity of the class is reduced, and what responsibilities are clearly defined;
● The readability is improved, and the complexity is reduced, so of course the readability is improved;
● The maintainability is improved, and the readability is improved, of course it is easier Maintained;
● The risk caused by the change is reduced, and the change is essential. If the single responsibility of the interface is done well, an interface modification will only affect the corresponding implementation class, and have no effect on other interfaces, which will affect the expansion of the system. Sexuality and maintainability are very helpful.
ps: The interface must have a single responsibility, and the design of the class should be designed so that there is only one reason for the change.
The single responsibility principle proposes a standard for writing programs, using "responsibility" or "reason for change" to measure whether the interface or class is well designed, but "responsibility" and "reason for change" are not measurable and vary from project to project. Varies by environment.
● Liskov Substitution Principle: Liskov Substitution Principle
Definition: Functions that use pointers or references to base classes must be able to
use objects of derived classes without knowing it.
(All references to base classes must be able to transparently use objects of its subclasses .)
In layman's terms, as long as the parent class can appear, the subclass can appear, and replacing it with a subclass will not cause any errors or exceptions. Users may not need to know whether it is a parent class or a subclass. However, the reverse is not possible. Where there are subclasses, the parent class may not be able to adapt.
The four meanings contained in the definition:
1. The subclass must fully implement the method of the parent class
2. The subclass can have its own personality
3. The input parameters can be enlarged when overriding or implementing the method of the parent class
If the input parameter type of the parent class is greater than the input parameter type of the subclass, there will be places where the parent class exists, but the subclass may not exist, because once the subclass is passed in as a parameter, the caller is likely to enter the method category of the subclass.

  1. When overriding or implementing the method of the parent class, the output result can be reduced. The
    return value of a method of the parent class is a type T, and the return value of the same method (overloaded or overridden) of the subclass is S, then the Liskov substitution principle It is required that S must be less than or equal to T, that is, either S and T
    are the same type, or S is a subclass of T.
    ● Interface Segregation Principle: Interface Segregation Principle
    There are two types of interfaces:
    Object Interface: A class in Java is also an interface
    Class Interface: Interface
    isolation defined by the Interface keyword is often used in Java: to establish a single Interface, don't create a bloated and huge interface; that is, the interface should be as detailed as possible, and the methods in the interface should be as few as possible.
    The difference between the principle of interface isolation and the principle of single responsibility: the principle of interface isolation is different from the perspective of single responsibility. Single responsibility requires a single class and interface responsibility, focusing on responsibility, which is
    the division The principle of interface segregation requires that the methods of the interface be as few as possible.
    ● Dependence Inversion Principle: Dependency Inversion Principle
    Original definition:
    ① High-level modules should not depend on low-level modules, both should depend on their abstractions;
    ② Abstractions should not depend on details (implementation classes);
    ③ Details should depend on abstractions.
    The embodiment of the dependency inversion principle in the Java language:
    ①The dependencies between modules occur through abstraction, and there is no direct dependency between the implementation classes, and the dependencies are
    generated through interfaces or abstract classes;
    ②Interfaces or abstract classes do not depend on Implementation class;
    ③ Implementation class depends on interface or abstract class.
    Three ways to write dependencies:
    ①Constructor transfers dependent objects (constructor injection)
    ②Setter method transfers dependent objects (setter dependency injection)
    ③Interface declares dependent objects (interface injection)
    Principle of use:
    The essence of the dependency inversion principle is to use abstraction (interface or Abstract class) makes the implementation of each class or module independent of each other, does not affect each other, and realizes loose coupling between modules. How do we use this rule in the project? Just
    follow the following rules:
    ①Every class should have an interface or an abstract class as much as possible, or both an abstract class and an interface. ②The surface type of a variable should
    be an interface or an abstract class as much as possible.
    Concrete class derivation (as long as there are no more than two levels of inheritance is tolerable)
    ④Try not to overwrite the method of the base class
    ⑤Use in conjunction with the Liskov substitution principle
    Open Closed Principle: Definition of the Open Closed Principle
    : Software entities should be open to extensions closure.
    Its implication is that a software entity should implement changes through extensions, rather than through modification of existing codes.
    Software entities: modules, abstractions, classes, and methods that are divided according to certain logical rules in a project or software product.
    Three types of changes:
    ①Logic change
    Only one logic is changed without involving other modules. For example, the original algorithm is a b+c, and now it needs to be changed to a b*c. You can modify the method in the original class The premise is that all dependent or
    associated classes are processed according to the same logic.
    ② Submodule changes
    A module change will affect other modules, especially a low-level module change will inevitably cause a high-level module change, so when the change is completed through expansion, high-level module modification is inevitable.
    ③ Visible view changes
    Visible views are interfaces provided to customers, such as JSP programs, Swing interfaces, etc. Changes in this part will generally cause chain reactions (especially in domestic projects, and generally do not affect
    too much ). Changes can be done through expansion, depending on whether our original design is flexible.

Guess you like

Origin blog.csdn.net/dreamer23/article/details/109356679