Explain the six principles of SOLID with code

Six principles

Single Responsibility Principle

definition

definition:

确保单例类只有一个实例,并且这个单例类提供一个函数接口让其他类获取到这个唯一的实例。

Explanation: A class is only responsible for one responsibility, and there should not be more than one reason for the class to change.

code explanation

For example, a class records the names of some foods, but at the same time records the practices of the foods. The former belongs to business objects, the latter belongs to business logic. According to the principle of single responsibility, we need to separate business and data

Not following the single principle

public class Foods {
    private String fish;
    private String meat;

    public String getFish() {
        return fish;
    }

    public void setFish(String fish) {
        this.fish = fish;
    }

    public String getMeat() {
        return meat;
    }

    public void setMeat(String meat) {
        this.meat = meat;
    }
    public void RedCookedFish(){
        //do something...
    }
    public void RedCookedMeat(){
        //do something...
    }
}

abide by the single principle

public class Foods {
    private String fish;
    private String meat;

    public String getFish() {
        return fish;
    }

    public void setFish(String fish) {
        this.fish = fish;
    }

    public String getMeat() {
        return meat;
    }

    public void setMeat(String meat) {
        this.meat = meat;
    }
}
public class Practices {
    public void RedCookedFish(){
    //do something...
    }
    public void RedCookedMeat(){
    //do something...
    }
}

open-closed principle

definition

定义:一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。

When a system has new needs, we do not want to modify the original functional class, which will destroy the original logic, so that new bugs appear, so we try to implement new functions by extending the system when designing the system. Simple That said, let's make good use of inheritance and interfaces.

code explanation

For example, there is an animal, which has two attributes: name and movement mode. When it becomes an adult, it needs to meet the opposite sex, and it needs to increase the function of reproduction. We expand new functions through inheritance or interface, and follow the open-closed principle.

public class Animal {
    private String mName;
    private String mMovementMode;
    public Animal(String mName,String mMovementMode){
        this.mName = mName;
        this.mMovementMode = mMovementMode;
    }

    public String getmName() {
        return mName;
    }

    public String getmMovementMode() {
        return mMovementMode;
    }
}
public class Multiply extends Animal {
    public Multiply(String mName, String mMovementMode) {
        super( mName, mMovementMode );
    }
    public void MultiplyMethod(){
    //do something...
    }
}

Liskov Substitution Principle

definition

定义1:如果对每一个类型为 T1的对象 o1,都有类型为 T2 的对象o2,使得以 T1定义的所有程序
P 在所有的对象 o1 都代换成 o2 时,程序 P 的行为没有发生变化,那么类型 T2 是类型 T1 的子类
型。
定义2:所有引用基类的地方必须能透明地使用其子类的对象

Explanation: For example, the abstract method of an abstract class, the subclass must implement

code explanation

For example, an animal class has an attribute of movement mode, and other specific animals, such as fish, eagle, etc., need to inherit its methods to realize their own movement modes.

public abstract class Animal {
    public abstract void MultiplyMethod(String Multiply);
}
public class Fish extends Animal {
    @Override
    public void MultiplyMethod(String Multiply) {
        // set Multiply Method
    }
}

Dependency Inversion Principle

definition

定义:高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。

The core idea of ​​the Dependency Inversion Principle is interface-oriented programming.

code explanation

For example, the popular programming languages ​​at this stage, java, c, python, etc., but with the passage of time and the development of science and technology, new languages ​​will be generated according to different needs. If we need to add one by one in a class, it would be too much trouble, and it would be much simpler to configure it using an interface.

Failure to comply with the principle of dependency leads to

class C{
    public String get(){
        return "C";
    }
}
class Java{
    public String get(){
        return "Java";
    }
}
class Python{
    public String get(){
        return "Python";
    }
}
class GetLanguage{
    public GetLanguage(){

    }
    public void getLanguage(C c){
        Log.d( "Language",c.get() );
    }
    public void getLanguage(Java java){
        Log.d( "Language",java.get() );
    }
}
 GetLanguage language = new GetLanguage();
        language.getLanguage( new C() );
        language.getLanguage( new Java() );

Adhere to the Dependency Cause Principle

define interface

public interface ILanguage {
    String get();
}
public class Language {
   public void getLanguage(ILanguage iLanguage){
       Log.d( "Language",iLanguage.get() );
   }
}
 Language language = new Language();
        language.getLanguage( new ILanguage() {
            @Override
            public String get() {
                return "C";
            }
        } );

insert image description here

Interface Segregation Principle

definition

定义:客户端不应该依赖它不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。

Simply put, a class only needs to implement the methods it needs, and irrelevant methods do not need to be implemented

code explanation

For example, an interface implements all the movement methods of animals, such as: running, crawling, swimming, flying, and jumping. Eagles only need to implement flying, and dogs only need to implement running, but to implement this interface, all methods must be implemented, which will be very bloated, and some methods do not need to be implemented. We only need to split them into four interfaces, different animals, and different movement methods.

Failure to follow the principle of interface isolation

public interface IAnimal {
    void run();
    void swim();
    void climb();
    void fly();
}
class Dog implements IAnimal{

    @Override
    public void run() {

    }

    @Override
    public void swim() {

    }

    @Override
    public void climb() {

    }

    @Override
    public void fly() {

    }
}

Adhere to the principle of interface isolation

public interface  Swim{
        void swim();
    }
    public interface  Run{
        void run();
    }
    public interface  Climb{
        void climb();
    }
    public interface  Fly{
        void fly();
    }
class Dog implements Run{

        @Override
        public void run() {

        }
    }

Demeter principle

definition

定义:一个对象应该对其他对象保持最少的了解。

code explanation

Suppose a class implements four methods of addition, subtraction, multiplication and division, and at the same time implements type judgment on the values ​​to be operated in the addition, subtraction, multiplication and division methods. Type judgment also implements range judgment. We only need to expose the four methods of addition, subtraction, multiplication and division, and the rest of the methods do not need to be exposed.

public class Operation {
    public Object Add(Object num1,Object num2){
       Object flag = JudgeType(num1,num2);
       int num = (Integer) flag;
       switch (num){
           case 0:
               return (Integer)num1 + (Integer)num2;
           case 1:
               return (Double)num1 + (Double) num2;
            default:
                return null;
       }
    }
    private void Sub(Object num1,Object num2){

    }
    private void Ride(Object num1,Object num2){

    }
    private void Division(Object num1,Object num2){

    }
    private Object JudgeType(Object num1,Object num2){
        if (num1 instanceof Integer){
          return 0;
        }else if (num1 instanceof Double){
            return 1;
        }
        return 3;
    }
//    private boolean JudgeIntRange(int num){
//        if (num < 65535 && num > -65535){
//            intFlag = true;
//            return true;
//        }
//        intFlag = false;
//        return false;
//    }
}
Operation operation = new Operation();
Log.d( "Result=",operation.Add( 1,1 )+"" );
2021-10-27 21:27:32.893 25595-25595/com.franzliszt.solid D/Result=: 2

Guess you like

Origin blog.csdn.net/News53231323/article/details/120999627
Recommended