search
HomeJavajavaTutorialOverview of Java's 23 design patterns and 6 major design pattern principles

Analysis of 23 design patterns in Java

1. Overview of design patterns

Generally speaking, design patterns are divided into three categories:

There are five creative patterns: factory method pattern, abstract factory pattern, singleton pattern, builder pattern, and prototype pattern.

There are seven structural modes: adapter mode, decorator mode, proxy mode, appearance mode, bridge mode, combination mode, and flyweight mode.

Behavioral patterns, eleven in total: strategy pattern, template method pattern, observer pattern, iterative sub pattern, chain of responsibility pattern, command pattern, memo pattern, state pattern, visitor pattern, mediator pattern , interpreter mode.

The details are as follows:

The creation types are:

1. Singleton, singleton mode: ensure that a class has only one instance and provide an access method to it Global access

Point

2. Abstract Factory: Provides an interface for creating a series of related or interdependent objects,

without specifying their specific classes.

3. Factory Method: Factory method: Define an interface for creating objects and let subclasses decide which class to instantiate. Factory Method delays the instantiation of a class until the subclass kind.

4. Builder, construction mode: separates the construction of a complex object from its representation, so that the same construction process can create different representations.

5. Prototype, prototype mode: Use prototype instances to specify the types of objects to be created, and create new objects by copying these prototypes.

Behavioral types are:

6. Iterator, iterator mode: Provides a method to sequentially access each element of an aggregate object without exposing the object's internal representation.

7. Observer, Observer pattern: Define one-to-many dependencies between objects. When the status of an object changes, all objects that depend on it are notified and automatically updated. .

8. Template Method: Define the skeleton of an algorithm in operation and defer some steps to subclasses. TemplateMethod allows subclasses to not change the structure of an algorithm. That is, you can redefine certain specific steps of the algorithm.

9. Command, command mode: encapsulates a request as an object, allowing you to parameterize clients with different requests, queue requests and record request logs, and Supports undoable operations.

10. State, state mode: allows an object to change its behavior when its internal state changes. The object appears to have changed its class.

11. Strategy, strategy pattern: Define a series of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the algorithms to be independent of the users who use them. client.

12. China of Responsibility, chain of responsibility model: Give multiple objects the opportunity to process requests, thereby avoiding the coupling relationship between the sender and receiver of the request

13. Mediator, mediator pattern: Use a mediator object to encapsulate a series of object interactions.

14. Visitor, visitor mode: represents an operation that acts on each element in an object structure. It allows you to define the role without changing the class of each element. A new operation for this element.

15. Interpreter, interpreter mode: given a language, define a representation of its grammar, and define a

interpreter that uses this representation to interpret sentences in the language.

16. Memento, memo mode: Capture the internal state of an object and save this state outside the object without destroying the object.

Structural types include:

17. Composite, combination mode: combine objects into a tree structure to represent the relationship between parts and the whole, Composite enables users to use single objects and composite objects consistently.

18. Facade, appearance mode: Provides a consistent interface for a set of interfaces in the subsystem. Fa?ade provides a high-level interface, which makes the subsystem easier to use. .

19. Proxy, proxy mode: Provide a proxy for other objects to control access to this object

20. Adapter Adapter mode: Convert one type of interface into another interface that the customer wants. The Adapter mode allows classes that cannot work together because of incompatible interfaces to work together.

21. Decrator, decoration mode: Dynamically add some additional responsibilities to an object. In terms of added functions, the Decorator mode is more flexible than generating subclasses.

22. Bridge, Bridge pattern: Separates the abstract part from its implementation part so that they can change independently.

Twenty-three, Flyweight, flyweight mode

In fact, there are two categories: concurrent mode and thread pool mode. Use a picture to describe it as a whole:

Overview of Javas 23 design patterns and 6 major design pattern principles

2. The six principles of design patterns

General Principle: Open Close Principle

The Open Close Principle means that it is open for expansion and closed for modification. When the program needs to be expanded, the original code cannot be modified, but the original code must be expanded to achieve a hot-swappable effect. So the summary in one sentence is: in order to make the program scalable and easy to maintain and upgrade. To achieve this effect, we need to use interfaces and abstract classes, etc. We will mention this in the specific design later.

1. Single Responsibility Principle

There should not be more than one reason for class changes, that is to say, each class should implement a single responsibility. If not, the class should be split.

2. Liskov Substitution Principle (Liskov Substitution Principle)

Liskov Substitution Principle (Liskov Substitution Principle LSP) is one of the basic principles of object-oriented design-". In the Liskov Substitution Principle Say,

Anywhere a base class can appear, a subclass can definitely appear. LSP is the cornerstone of inheritance and reuse. Only when the derived class can replace the base class and the functionality of the software unit is not affected, Only the base class can be truly reused, and the derived class can also add new behaviors on the basis of the base class. The Liskov substitution principle is a supplement to the "open-closed" principle. The key steps to realize the "open-closed" principle It is abstraction. The inheritance relationship between the base class and the subclass is the specific implementation of abstraction, so the Liskov substitution principle is the specification of the specific steps to achieve abstraction. FromBaidu

Encyclopedia

In the principle of historical replacement, subclasses should try not to overwrite or overload methods of the parent class. Because the parent class represents a defined structure and interacts with the outside world through this standardized interface, subclasses should not destroy it casually.

3. Dependence Inversion Principle

This is the basis of the opening and closing principle. The specific content: interface-oriented programming, relying on abstraction rather than concreteness. Used when writing code When it is a concrete class, it does not interact with the concrete class, but with the upper interface of the concrete class.

4. Interface Segregation Principle

This principle means: each interface There are no methods that are not used by subclasses but must be implemented. Otherwise, the interface must be split. Using multiple isolated interfaces is better than using a single interface (multiple interface methods are collected into - An interface) is better.

5. Demeter Principle (Demeter Principle)

That is to say: the less a class knows about the classes it depends on, the better. That is to say, no matter how complex the dependent class is, the logic should be encapsulated inside the method and provided to the outside through the public method. In this way, when the dependent class changes, the impact on the class can be minimal.

Another expression of the least known principle is: only communicate with direct friends. As long as there is a coupling relationship between classes, it is called a friend relationship. Coupling

can be divided into dependence, association, aggregation, combination, etc. We Classes that appear in member variables, method parameters, and method return values ​​are called direct friends. Local variables and temporary variables are not direct friends. We require unfamiliar classes not to appear as local variables in the class.

6. Composite Reuse Principle

The principle is to try to use synthesis/aggregation first instead of using inheritance.

3. Java’s 23 Design Patterns A. Creation Patterns

Starting from this section, we will introduce in detail the concepts, application scenarios, etc. of the 23 design patterns in Java, and combine their Characteristics and principles of design patterns are analyzed.

First of all, the simple factory pattern does not belong to the patterns involved in 23. Simple factories are generally divided into: ordinary simple factories, multi-method simple factories, and static method simple factories.

0. Simple factory mode

The simple factory mode mode is divided into three types: 01. Ordinary

is to create a factory class to implement some classes that implement the same interface. Create an instance. First, look at the relationship diagram:

Overview of Javas 23 design patterns and 6 major design pattern principles# Examples are as follows: (Let’s give an example of sending emails and text messages) First, create a common interface between the two:

public interface Sender {
    public void Send();
}

Secondly, create the implementation class:

public class MailSender implements Sender {
    @Override
    public void Send() {
    System.out.println("this is mailsender!");
    }
}

public class SmsSender implements Sender {
    @Override
    public void Send() {
    System.out.println("this is sms sender!");
    }
}

Finally, build the factory class:

public class SendFactory {
    public Sender  produce(String type){
    if ("mail" .equals(type) {
        return new MailSender( );
    }else if("sms" .equals(type)){
        return new SmsSender();
    }else{
        System. out . println("请输入正确的类型!"); 
        return null;)
    }
}

Let’s test it:

public class FactoryTest {
    public static void main(String[] args) {
        SendFactory factory = new SendFactory();
        Sender sender = factory.produce("sms");
        sender.Send();
    }
}

Output: this is sms sender!

02. Multiple methods

is an improvement over the ordinary factory method pattern. In the ordinary factory method pattern, if the passed string is wrong, the object cannot be created correctly, while the multiple factory method pattern It provides multiple factory methods to create objects separately. Relationship diagram:

Overview of Javas 23 design patterns and 6 major design pattern principles Modify the above code and change the SendFactory class, as follows:

public class SendFactory {
    public Sender produceMail(){
        return new MailSender();   
    }        
    public Sender produceSms(){
        return new SmsSender();
    }
}

The test class is as follows:

public class FactoryTest{
    public static void main(String[] args) {
        SendFactory factory = new SendFactory( );
        Sender sender = factory.produceMail();
        sender.Send();
    }
}

Output: this is mailsender!

Related articles:

Java Design Patterns - Six Principles of Design Patterns

24 Design Patterns and 7 Principles in Java

The above is the detailed content of Overview of Java's 23 design patterns and 6 major design pattern principles. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Are there any areas where Java requires platform-specific configuration or tuning?Are there any areas where Java requires platform-specific configuration or tuning?Apr 29, 2025 am 12:11 AM

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

What are some tools or libraries that can help you address platform-specific challenges in Java development?What are some tools or libraries that can help you address platform-specific challenges in Java development?Apr 29, 2025 am 12:01 AM

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment