Principles of opening and closing in software

        In the software design mode, there is an Open-Closed Principle (OCP), which is used in many ways. It is introduced below.
        1. The definition
        of the opening and closing principle is changed by adding code instead of modifying the source code;
        2. Case
        1.1 Original design ver1.1

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
using namespace std;


class Banker
{
    
    
public:
	void save(){
    
    
		cout << "save" << endl;
	}

	void trans(){
    
    
		cout << "trans" << endl;
	}

	void pay(){
    
    
		cout << "pay" << endl;
	}
};


int main(void)
{
    
    
	Banker bk;
	bk.trans();
	bk.save();	

	return 0;
}

        1.2 Design ver1.2 with the principle of opening and closing

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
using namespace std;


class AbstractBanker
{
    
    
public:
	virtual void busi() = 0;
};

class SaveBanker :public AbstractBanker
{
    
    
public:
	virtual void busi(){
    
    
		cout << "save" << endl;
	}
};

class TransBanker :public AbstractBanker
{
    
    
public:
	virtual void busi(){
    
    
		cout << "Trans" << endl;
	}
};

class PayBanker :public AbstractBanker
{
    
    
public:
	virtual void busi(){
    
    
		cout << "save" << endl;
	}
};



int main(void)
{
    
    
	AbstractBanker *saveBanker = new SaveBanker; 
	saveBanker->busi();

	delete saveBanker;	

	return 0;
}

        Version ver1.2 has better maintainability and scalability than ver1.1 code.

Guess you like

Origin blog.csdn.net/sanqima/article/details/105328179