gpt4 book ai didi

c++ - 如何应用注册表模式使 "select class depend on input"服从开闭原则?

转载 作者:行者123 更新时间:2023-11-28 05:06:09 25 4
gpt4 key购买 nike

例如,我有一些水果:

水果.h

#ifndef __Fruit__
#define __Fruit__
#include <string>
class Fruit{
public:
virtual void hi(std::string username)=0;
};
#endif

苹果.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());
}
};

橙色.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());
}
};

我需要根据输入的字符串来决定使用哪个:

#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;
}

我知道它不遵守开闭原则,因为添加一个新的 Fruit 需要添加一个新的 if-else 条件来映射到正确的函数。听说registry模式可以让这个case遵守开闭原则,是真的吗?如果是这样,如何在这里实现注册表模式?

最佳答案

这在代码方面可能会变得非常冗长,所以我使用单词代替。definition of the registry pattern :

A registry is a global association from keys to objects, allowing the objects to be reached from anywhere. It involves two methods: one that takes a key and an object and add objects to the registry and one that takes a key and returns the object for the key

这里的问题是注册表不知道如何构建对象,只知道如何检索它。这与创建模式有显着差异。

基本上你的水果应该可以变成

#include <string>
class Fruit{
public:
virtual std::string key() const = 0;
virtual void hi(std::string username) = 0;
};

现在你引入一个注册表

class FruitRegistry final {
public:
bool register(Fruit* fruit);
Fruit* locate(std::string key);

private:
std::map<string, Fruit*> registry;
};

无论什么水果,注册/检索水果的方式应该是一样的。这里可以使用映射字符串来实现。您还可以设计 fruit 类,使其使用 accept 方法,这在输入复杂时非常有用(考虑根据其描述初始化水果)。

什么时候有用?当它在接口(interface)后面使用以访问一种类型的资源时,例如 img.load("cats.jpg")。 jpg、bmp、png 格式非常不同,可能需要为每个单独的引擎,或者一个用于 jpg,另一个用于 bmp 和 png。但是用户并不关心这些细节。请注意,将来可以在不影响图像加载的情况下添加越来越多的图像类型。

问题是要提供漂亮的img.load("cats.jpg"),下面的注册表机制设计起来可能很复杂。你需要问问自己:

  • 用户是否关心苹果和橙子(如果不止于此,您不需要注册)?还是他只是想吃个水果?
  • 实现注册表后吃水果有多容易? (应该是单行)
  • 可以多久或多长时间添加一次新型水果? (应该是永远的)
  • 水果有何不同? (应该是完全的,就是能吃)

关于c++ - 如何应用注册表模式使 "select class depend on input"服从开闭原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44716570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com