Software Design Principles - The Open-Closed Principle

1.1 Open and closed principle

Open for extension, closed for modification . When the program needs to be expanded, the original code cannot be modified to achieve a hot-plug effect. In short, it is to make the program expandable, easy to maintain and upgrade.

To achieve this effect, we need to use interfaces and abstract classes.

Because the abstraction is flexible and adaptable, as long as the abstraction is reasonable, the stability of the software architecture can be basically maintained. The volatile details in the software can be extended from the implementation class derived from abstraction. When the software needs to change, it is only necessary to re-derive an implementation class to extend according to the requirements.

The following takes LOLthe skin of as an example to introduce the application of the open-closed principle.

【Example】LOLThe skin design.

Analysis: Each hero has its own skin, these skins have common characteristics, an abstract class (AbstractSkin) can be defined for them, and each specific skin (DefaultSkin and MetalGearSkin) is its subclass. If the hero class wants to use the skin, it only needs to rely on the abstract class of the skin, use the abstract class to accept the subclass, and call the method of the subclass, so that every time the skin is changed, there is no need to change the hero class, and there is no need to modify the original class. code, so it satisfies the open-closed principle.

 

 Skin interface:

public abstract class AbstractSkin {

    /*
        显示皮肤类
     */
    public abstract void display();

}

Default skin:

public class DefaultSkin extends AbstractSkin{


    @Override
    public void display() {
        System.out.println("默认皮肤类");
    }
}

Metal Gear Solid Skins:

public class MetalGearSkin extends AbstractSkin{


    @Override
    public void display() {
        System.out.println("合金装备亚索");
    }
}

Hero class:

public class YasuoHero {

    private AbstractSkin skin;

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

    public void display(){
        skin.display();
    }

}

Test class:

public class Client {

    public static void main(String[] args) {
        //1、创建英雄亚索
        YasuoHero yasuo = new YasuoHero();
        //2、创建皮肤对象
//        DefaultSkin skin = new DefaultSkin();
        MetalGearSkin skin = new MetalGearSkin();
        yasuo.setSkin(skin);
        yasuo.display();

    }
}

Guess you like

Origin blog.csdn.net/qq_45171957/article/details/122224271