The concept of the open close principle

The open closed principle is simply open for extension, closed for modification.

When the program needs to be expanded, the original code should not be modified

To achieve this effect, you need to use interfaces or abstract classes. When the program needs to change, or need to add something that is not already there, you don’t need to modify the original code, just need to create a new implementation class to extend it.

The case for the open closed principle

We usually in the development of the most contact tools should be comfortable method, of course, here refers to the third-party input method such as Sogou input method, sogou input method skin function is to follow the open and closed principle. One skin interface/abstract class, multiple implementation classes. We can use the native default input skin, or we can download and use other skins.

Simple simulation sogou input method open – close principle

Write an abstract class for a skin with an abstract method that shows the skin

public abstract class Skin {

    /** * show skin */
    public abstract void display(a);
}
Copy the code

Write implementations of three skins

public class DefaultSkin extends Skin {

    /** * Rewrite the skin display method */
    @Override
    public void display(a) {
        System.out.println("Show default skin"); }}Copy the code
public class ExternalFirstSkin extends Skin{

    /** * Rewrite the skin display method */
    @Override
    public void display(a) {
        System.out.println("Show third Party skin 1"); }}Copy the code
public class ExternalSecondSkin extends Skin {

    /** * Rewrite the skin display method */
    @Override
    public void display(a) {
        System.out.println("Show third Party Skin 2"); }}Copy the code

Write sogou input method ontology

public class SougouInput {


    private Skin skin = new DefaultSkin();

    public void setSkin(Skin skin) {
        this.skin = skin;
    }


    public void display(a) { skin.display(); }}Copy the code

Initialize skin to default skin. That is, let it be the default skin when no skin is set

test

public class Test {

    public static void main(String[] args) {
        SougouInput sougouInput = new SougouInput();
        sougouInput.display();

        sougouInput.setSkin(new ExternalFirstSkin());
        sougouInput.display();

        sougouInput.setSkin(newExternalSecondSkin()); sougouInput.display(); }}Copy the code

When we need to add a new Skin, we only need to inherit the Skin abstract class, rewrite the display method, and then use sogou input method to set the Skin, which is one of the six principles to follow the open and close principle of software design.

When we have a new requirement (a new skin), we don’t need to change the original code logic (the original skin implementation class), but simply add a new derived class to implement the interface/abstract class