Adapter of java design pattern

Adapter of java design pattern

Although I have been learning java for a while, << thinking in java >> is still a bit difficult at first glance. The reason is that there are many design patterns in the chapters. At first glance, these design patterns cannot fully understand the truth, so I decided to Let's take a brief look at some design patterns in java. Since the content of this article contains code written by myself, it cannot be guaranteed that the ideas of design patterns can be reflected in its original form.

adapter

  1. Scenario introduction: If Tom is a math teacher, he has math genes since he was a child, and Jack is a physical education teacher, he has sports genes since he was a child.
public interface MathGene {
    void teachMath();
}

public interface SportsGene {
    void teachSports();
}

public class Tom implements MathGene {
    @Override
    public void teachMath() {
        System.out.println("I know math a lots.");
    }
}

public class Jack implements SportsGene {
    @Override
    public void teachSports() {
        System.out.println("I teach sports only!");
    }
}

An existing school needs a math teacher to teach math.

public class NeedMathTeacher {
    void teach(MathGene teacher){
        teacher.teachMath();
    }
}

Theoretically, the school would not hire Jack, so how could a physical education teacher teach math? But Jack was very tight recently, so he decided to try the job application. But he needed to "reshape" himself to be like a math teacher, so he I spent money to find a professional fraud agency Adapter. This Adapter allows those with sports genes to "teach mathematics", but in fact, when teaching mathematics, their brains are still full of sports knowledge.

public class Adapter implements MathGene {
    private SportsGene teacher;
    public Adapter(SportsGene teacher){
        this.teacher = teacher;
    }
    @Override
    public void teachMath() {
        teacher.teachSports();
    }
}

After going through the Adapter, Jack can blatantly teach math.

public class Test {
    public static void main(String[] args) {
        NeedMathTeacher school = new NeedMathTeacher();
        school.teach(new Adapter(new Jack())); // output : I teach sports only!
    }
}

summary

  1. For example, now a method needs an object whose base class/interface is type A to do something, but now I only have type B, then I can write an Adapter that implements A, Adapter has members of type B, and this Adapter overrides The method of type A, and the content of these methods actually contains the method of calling type B, and then you can happily use this Adapter as type A.

Guess you like

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