Design Principles of Design Patterns

Six design principles

When it comes to design patterns, we have to talk about the six design principles of design patterns;

1. Single responsibility principle (SRP :Single responsibility principle)
2. Liskov Substitution Principle (LSP : Liskov Substitution Principle)
3. Dependency inversion principle (DIP: Dependency inversion principle)
4. Interface Segregation Principles (ISP: interface-segregation principles)
5. Demeter's Law (LKP: Least Knowledge Principle)
6. Open-Closed Principle (OCP: Open Closed Principle)

The above are the six principles of design mode, and the following are some points summarized in actual combat (will be added later):

  • Find out where changes may be needed in the application, isolate them, and don't mix them with code that doesn't need to change

         Explanation: Take out and "encapsulate" the parts that change so that other parts are not affected.

         Result: fewer unintended consequences of code changes and more resilient systems

  • Program for the interface, not for the implementation
  • More composition, less inheritance

Examples are as follows:

public abstract calss Duck {

     FlyBehavior flyBehavior;

     QuackBehavior quackBehavior;

     

     public abstract void display();

 

     public void performFly() {

          flyBehavior.fly();

     }

     

     public void performQuack() {

         quackBehavior.quack();

     }

     

     public void swim() {

        System.out.println("All ducks float.");

     }

     //Set two set methods to set different behaviors

     public void setFlyBehavior(FlyBehavior fb) {

          flyBehavior = fb;

     }

 

     public void setQuackBehavior(QuackBehavior qb) {

          quackBehavior = qb;

     }

}

 

public interface FlyBehavior {

     public void fly();

}

 

public class FlyWithWings implements FlyBehavior {

     public void fly() {

          System.out.println("I'm Flying!");

     }

}

 

public interface QuackBehavior {

     public void quack();

}

 

public class Quack implents QuackBehavior {

      public void quack() {

           System.out.println("Quack");

      }

}

 

public class ModelDuck extends Duck {

      public ModelDuck () {

             flyBehavior = new FlyWithWings();

             quackBehavior = newQuack(); 

      }

 

      public void display() {

          System.out.println("I'm a model duck!");

      }

}

 

public class Test {

     public static void main(String[] args) {

             Duck duck = new ModelDuck();

             duck.performQuack();

             duck.performFly();

     }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326201965&siteId=291194637