java Design Pattern Understanding Depends on Abstraction Not on Concrete Analysis

  • 2021-11-29 06:53:25
  • OfStack

In the object-oriented design principle, it is required to "rely on abstraction, not on concreteness", which many people don't understand. Let me talk about my own understanding here. Let's take a look at the following code first


class A{
 public void swim(){
    Dog dog = new Dog();
    dog.move();
  }
}

An Dog object is defined in swim method, so no matter which object calls this method, 1 must be "dog crawling", and the objects of swim and Dog are tightly coupled, so it is impossible for us to replace them with ducks.

If the code is changed like this, we define an interface of an animal, and the interface defines an move method.


interface Animal
{
   void move();
}

Let dogs and ducks implement this interface with the following code


public class Dog implements Animal
{
   override
   public void move(){
     // Dog crawling 
   } 
}
public class Duck implements Animal
{
   override
   public void move(){
     //8 Word step 
   } 
}

class A code is changed to the following code:


class A
{
  private Animal animal;
  public A(Animal animal)
  {
      this.animal = animal; 
  }

  public void swim(){   
    animal.move();
  }
}

class A depends on the interface (abstract) Animal, and dog, duck (concrete) has no 1-point relationship, when we inject the object is a dog, then perform dog crawl, when we inject the object is a duck, then perform 8-step. This is the concrete meaning of "relying on abstraction, not on concreteness". This advantage is that the program is well extended. If you want to use frogs to swim, I only need to create a frog class that realizes Animal interface, inject frog objects into A class, and then you can perform frog breaststroke. The code in A is completely closed.

The above is the java design pattern understanding depends on the abstraction does not depend on the concrete analysis the detailed content, more about java depends on the abstract design pattern information please pay attention to this site other related articles!


Related articles: