This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
The open closed principle
(1) Definition: open for extension, closed for modification. In plain English, software entities should be extended as far as possible without modifying the original code.
(2) Implementation analysis: Abstraction is the key to realize the open and close principle. We usually abstract and close things by extracting the commonness of things, and then provide interfaces to expand and open the differences of things.
(3) Example: In games, it is common for players to choose characters to play.
1) Our original scheme may be as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Client : MonoBehaviour {
void Start () {
SelectSoldier();
}
void SelectSoldier()
{
Soldier soldier = new Soldier();
print("Chosen"+ soldier.name);
}
void SelectMaster()
{
Master master = new Master();
print("Chosen"+ master.name); }}public class Soldier: Character
{
public Soldier()
{
name = "Soldier"; }}public class Master : Character
{
public Master()
{
name = "Master"; }}Copy the code
2) This obviously doesn’t fit our on/off principle, because every time we add a character, such as an assassin, we have to change the Client code. So we need to refactor as follows:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Client : MonoBehaviour {
void Start () {
Select(new Soldier());
}
void Select(Character character)
{
print("Chose the warrior."+character.name); }}public abstract class Character
{
public string name;
public Character()
{
name = "Character"; }}public class Soldier: Character
{
public Soldier()
{
name = "Soldier"; }}public class Master : Character
{
public Master()
{
name = "Master"; }}Copy the code
Now when we add an assassin, we just create a new class that inherits the object class, and we don’t need to change the original code.