purpose

Make sure that new and old code is migrated gradually without affecting the development of new features

The example code

A recent hangzhou women’s bizarre aroused the attention of all the missing things, generally is about a woman who was reported missing, community monitoring all haven’t been able to monitor how to leave the village, the present results is reorganization of the family’s husband because interest will be the death of the resin and thrown into the septic tank, after light alarm in an interview, etc, The grapevine says he asked his wife, “Do I have a chance? “,,,,,

Paint dragon tiger difficult to draw the bone, when one knows surface heart, originally is the reorganization of the family, woman is similar to the one of my old husband, replaced with new people, without transition better, just as we want to reconstruct a class in a complex system, the method is finished to replace it may cause increase in the number of uncertainty and risk in time, We’d better replace similar interfaces one by one. Gradually launched

Strangler mode

Define a husband interface:

public interface Man { void eat(); void drink(); void sleep(); }Copy the code

Older implementation classes:

Public class implements Man {@override public void eat() {system.out.println (" implements Man "); } @override public void drink() {system.out.println (); } @override public void sleep() {system.out.println ("8 to 8 "); }}Copy the code

New implementation class:

Public class implements Man {@override public void eat() {system.out.println (" implements Man "); } @override public void drink() {system.out.println (" I like beer "); } @override public void sleep() {throw new RuntimeException(); }}Copy the code

Transition:

public class HalfMan implements Man {    private Man oldMan;    private NewMan newMan;    public HalfMan(Man oldMan, NewMan newMan) {        this.oldMan = oldMan;        this.newMan = newMan;    }    @Override    public void eat() {        newMan.eat();    }    @Override    public void drink() {        newMan.drink();    }    @Override    public void sleep() {        oldMan.sleep();    }}
Copy the code

Usage:

public static void main(String[] args) { Man man = new HalfMan(new OldMan(),new NewMan()); man.sleep(); }Copy the code

Output:

8 to 8Copy the code

Class diagram: