Home Java javaTutorial Java Design Patterns-Six Principles of Design Patterns

Java Design Patterns-Six Principles of Design Patterns

Dec 12, 2016 pm 02:07 PM
java design patterns

Six Design Principles


Single Responsibility Principle


Don’t have more than one reason for class changes. In layman's terms, a class is only responsible for one responsibility.

Origin of the problem: Class T is responsible for two different responsibilities: responsibility P1 and responsibility P2. When class T needs to be modified due to changes in the requirements of responsibility P1, it may cause the function of responsibility P2 that was originally running normally to malfunction.

To sum up in one sentence: You can’t just put a small amount of code into one class


Richter substitution principle

1. Subclasses can implement the abstract methods of the parent class, but they cannot override the parent class. non-abstract method.

2. Subclasses can add their own unique methods.

3. When a method of a subclass overrides a method of a parent class, the preconditions of the method (that is, the formal parameters of the method) are looser than the input parameters of the parent class method.

4. When a method of a subclass implements an abstract method of the parent class, the postconditions of the method (i.e., the return value of the method) are more stringent than those of the parent class.

One sentence summary: Try not to rewrite the implemented methods of the parent class. You can use interfaces and other methods to bypass the

Dependency Inversion Principle

High-level modules should not depend on low-level modules, both should rely on their abstractions ;Abstraction should not depend on details; details should depend on abstraction.

Here is an example to illustrate:

import java.util.LinkedList;  
import java.util.Queue;  
  
  
  
interface IEAT  
{  
    public void eat();//抽象吃这个动作  
}  
class EatApple implements IEAT  
{  
  
    @Override  
    public void eat()   
    {  
        //这里是吃苹果  
        System.out.print("eat a apple");  
          
    }  
}  
class EatWater implements IEAT  
{  
  
    @Override  
    public void eat() {  
        // 这里是吃水  
        System.out.print("dringk water");  
          
    }  
      
}  
public class Human  
{  
    public void dosomething(IEAT ieat)//我爱吃东西,吃什么呢,看传入什么  
    {  
        ieat.eat();  
    }  
    /* 
    public void dosomething(String food)//我爱吃东西,吃什么呢,看传入什么 
    { 
        if(food.equals("apple")) 
        { 
            //吃苹果 
        } 
        if(food.equals("water")) 
        { 
            //喝水 
        } 
    } 
    */  
    public static void main(String[] args)  
    {  
        Human human=new Human();  
        /* 
        human.dosomething("apple"); 
        human.dosomething("water"); 
         */  
        //给你吃个苹果  
        human.dosomething(new EatApple());  
        //再给你喝点水  
        human.dosomething(new EatWater());  
    }  
}
Copy after login

The annotations are our commonly used methods. This method is very unsuitable for expansion, because if you want to eat bananas or watermelons, you have to write a lot of judgments in dosomething. As I write, I get mixed up.


So in one sentence: use abstract interfaces to describe the same action and reduce the coupling between the people and objects that implement the action


Principle of interface isolation



A client should not rely on interfaces it does not need; a class's dependence on another class should be based on the smallest interface.

The origin of the problem: Class A depends on class B through interface I, and class C depends on class D through interface I. If interface I is not the minimum interface for class A and class B, then class B and class D must implement them. They do not need to Methods.

To summarize in one sentence: Just like fish and humans, fish has two actions: swimming and gill breathing, and humans have two actions: walking and eating. These actions cannot be written in an interface, including all four actions. . It needs to be split into two interfaces specifically for fish and humans.



Demit's Law


Demit's Law is also called the least-known principle. It was first proposed in 1987 by Ian Holland of Northeastern University in the United States. In layman's terms, the less a class knows about the classes it depends on, the better. In other words, for the dependent class, no matter how complex the logic is, the logic should be encapsulated inside the class as much as possible, and no information will be leaked to the outside except the public methods provided.

This is a bit hard to remember. The summary is: father1<-child1, father2<-child2, father1 and father2 are subordinates. Father1 tries to access child2 through father2, and do not directly access child2 in the class. How can subordinates go there casually? As for the leader’s children, be careful if others say you are kidnapping


Opening and closing principle


There is nothing to say about this: try to achieve changes by extending the behavior of software entities rather than modifying existing code to effect change.


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles