for example, I have some Fruits:
Fruit.h
#ifndef __Fruit__
#define __Fruit__
#include <string>
class Fruit{
public:
virtual void hi(std::string username)=0;
};
#endif
Apple.h
#include "Fruit.h"
#include <stdio.h>
class Apple : public Fruit{
public:
virtual void hi(std::string message){
printf("Hi %s,I am apple\n",message.c_str());
}
};
Orange.h
#include "Fruit.h"
#include <stdio.h>
class Orange : public Fruit{
public:
virtual void hi(std::string message){
printf("Hi %s,I am orange\n",message.c_str());
}
};
I need to decide which to use according to input string:
#include "Apple.h"
#include "Orange.h"
int main(){
std::string username="abc";
std::string input="Orange";
if(input=="Apple"){
Apple().hi(username);
}else if(input=="Orange"){
Orange().hi(username);
}
return 0;
}
I know it doesn't obey open closed principle because adding a new Fruit needs to add a new if-else condition to map to the correct function. I heard registry pattern can make this case obey open closed principle, is it true? if so, how to implement registry pattern here?