1. Singleton
Basic concepts: Ensure that a class has only one instance and provide a global access point to access it.
Slacker type
public class Singleton { /* Hold private static instances to prevent references, where null is assigned to achieve delayed loading */ private static Singleton instance = null; /* Private construction methods to prevent instantiation */ private Singleton() {} /* 1:Lazy, Static Engineering Method, Creating Examples */ public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
Output: Singleton.getInstance().method();
Advantages: Delayed loading (to load when needed), suitable for single-threaded operation
Disadvantage: Threads are not safe, and it is easy to be asynchronized in multi-threads, such as frequent reads and writes of database objects.
Dual Thread Checking Mode
public class SingletonInner { private static volatile SingletonInner sInst = null; // volatile is added here < /** * Private constructors */ private SingletonInner() {} public static SingletonInner getInstance() { SingletonInner inst = sInst; // Create temporary variables here if (inst == null) { synchronized (SingletonInner.class) { inst = sInst; if (inst == null) { inst = new SingletonInner(); sInst = inst; } } } return inst; // Note that temporary variables are returned here } protected void method() { System.out.println("SingletonInner"); } }
Advantages: Delayed loading, thread safety
Disadvantage: Complex writing, not concise
Implementation of Internal Classes
public class SingletonInner { /** * Internal class implementation singleton pattern * Delayed loading to reduce memory overhead */ private static class SingletonHolder { private static SingletonInner instance = new SingletonInner(); } /** * Private constructors */ private SingletonInner() {} public static SingletonInner getInstance() { return SingletonHolder.instance; } protected void method() { System.out.println("SingletonInner"); } }
2. Factory Method
- Simple Factory: It is not conducive to the production of a series of products.
- Factory Method: Also known as Polymorphic Factory;
- Abstract Factory: Also known as toolbox, it generates product family, but it is not conducive to the production of new products.
This looks a little better sorted.
https://blog.csdn.net/fcvtb/article/details/85222439
3. Builder
Basic concepts: It is a design pattern of object construction, which can abstract the construction process of complex objects (abstract categories), so that different implementations of this abstract process can construct objects with different representations (attributes).
Builder pattern is to create complex objects step by step, which allows users to build complex objects only by specifying their type and content. Users do not know the details of the internal build. The Builder pattern is very similar to the abstract factory pattern, and the subtle differences may only be realized in repeated use.
-
Builder: Specify an abstract interface for each component that creates a Product object.
-
ConcreteBuilder: Implement the Builder interface to construct and assemble the components of the product, define and define the representations it creates, and provide an interface to retrieve the product
-
Director: Construct an object that uses the Builder interface.
-
Product: Represents the constructed complex object. Concreate Builder creates the internal representation of the product and defines its assembly process.
Why use
It is to decouple the process of building complex objects from their components. Note: It's the decoupling process and components.
Because a complex object not only has a lot of components, such as automobiles, many parts: wheels, steering wheels, engines, and various small parts, there are many parts, but far more than these, how to assemble these parts into a car, the assembly process is also complex (requires good assembly technology). Builder mode is to assemble parts and components. Cheng separation.
How to use
Firstly, assuming that a complex object is composed of multiple components, the Builder pattern separates the creation of complex objects from the creation of components, which are represented by Builder class and Director class respectively.
First, you need an interface that defines how to create components of complex objects:
public interface Builder { //Create Component A. Create Automotive Wheels, for example void buildPartA(); //Create component B, such as a car steering wheel void buildPartB(); //Create components C, such as automotive engines void buildPartC(); //Return the final assembly result (return to the final assembly car) //The assembly of the finished product is not done here, but transferred to the Director class below. //Thus the decoupling process and components are realized. Product getResult(); }
Build the final complex object with Director, and what is encapsulated in the Builder interface above is how to create a component (the complex object is composed of these components), that is, how the Director's content finally assembles the component into a finished product:
public class Director { private Builder builder; public Director( Builder builder ) { this.builder = builder; } // Component ParA ParB ParC finally composes complex objects //Here is the process of assembling the wheel steering wheel and engine into a car. public void construct() { builder.buildPartA(); builder.buildPartB(); builder.buildPartC(); } }
Concrete Builder:
- Builder is used to build or assemble the components of the product.
- Define and clarify what it is about to create.
- Provide an interface to retrieve the product.
public class ConcreteBuilder implements Builder { Part partA, partB, partC; public void buildPartA() { //Here's how to build it. } public void buildPartB() { //Here's how to build it. } public void buildPartC() { //Here's how to build it. } public Product getResult() { //Return the final assembly result } }
Complex object: Product:
public interface Product { }
Components of complex objects:
public interface Part { }
Let's see how to invoke the Builder pattern:
ConcreteBuilder builder = new ConcreteBuilder(); Director director = new Director( builder ); director.construct(); Product product = builder.getResult();
Application of Builder Model
In the actual use of Java, we often use the concept of "pool". When resource providers can not provide enough resources, and these resources need to be shared repeatedly by many users, they need to use the pool. Pool is actually a segment of memory. When there are some complex resources in the pool, such as the connection pool of the database, maybe sometimes a connection will be interrupted, if these "broken limbs" are recycled, the efficiency of memory utilization will be improved and the performance of the pool will be improved. Modify the Director class in Builder mode so that it can diagnose where the "amputated" part is broken, and then repair the part.
4. Prototype
Although the prototype pattern is a creation pattern, it has nothing to do with the engineering pattern. From the name, we can see that the idea of this pattern is to copy and clone an object as a prototype, and produce a new object similar to the original object. This summary will explain through the replication of the object. In Java, clone() is used to replicate objects. First, a prototype class is created.
public class Prototype implements Cloneable { public Object clone() throws CloneNotSupportedException { Prototype proto = (Prototype) super.clone(); return proto; } }
Simply, a prototype class only needs to implement Cloneable interface and override clone method, where clone method can be changed to any name, because Cloneable interface is an empty interface, you can arbitrarily define the method name of implementation class, such as cloneA or cloneB, because the emphasis here is super.clone(), which calls clone() method of Object, and clone() method of Object. In the class, clone() is native. Understanding the concepts of deep and shallow replication of objects:
- Shallow replication: After an object is replicated, the variables of the basic data type are recreated, and the reference type refers to the original object.
- Deep copy: After copying an object, both the basic data type and the reference type are recreated. Simply put, deep copy is completely and thoroughly duplicated, while shallow copy is not thoroughly duplicated.
public class Prototype implements Cloneable, Serializable { private static final long serialVersionUID = 1L; private String string; private SerializableObject obj; /* Shallow copy */ public Object clone() throws CloneNotSupportedException { Prototype proto = (Prototype) super.clone(); return proto; } /* Deep replication */ public Object deepClone() throws IOException, ClassNotFoundException { /* Write a binary stream to the current object */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); /* Read out new objects generated by binary streams */ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); } public String getString() { return string; } public void setString(String string) { this.string = string; } public SerializableObject getObj() { return obj; } public void setObj(SerializableObject obj) { this.obj = obj; } } class SerializableObject implements Serializable { private static final long serialVersionUID = 1L; }
Reprint
Twenty-three Design Patterns in the Development of Black Horse Programmer__java
https://www.cnblogs.com/miaozy/p/3685955.html