适用于预先存在的类层次结构的函数的最佳模式
Best pattern for functions that apply to a preexisting class hierarchy
我有一个现有的类层次结构,我无法修改
即系统发育树:
base
├── animal
│ ├── invertebrate
│ └── vertebrate
│ ├── amphibian
│ ├── bird
│ ├── fish
│ ├── mammal
│ └── reptile
└── plant
我需要为该层次结构中的对象构建一个函数库,即打印函数:
print_mammal_A()
print_mammal_B()
print_fish_A()
print_vertebrate_A()
print_vertebrate_B()
print_animal_A()
这些功能将根据需要进行开发。
每个类可能有多个函数。
显而易见的解决方案是创建一个映射目标层次结构的包装器的类层次结构。每个包装器实现它自己的函数,即:
class base_wrapper(){
base * base_ptr;
}
class animal_wrapper : base_wrapper{
void print_animal_A();
}
class vertebrate_wrapper : animal_wrapper {
void print_vertebrate_A();
void print_vertebrate_B();
}
我想知道允许以下任一项目的设计模式:
删除包装器继承(因此库开发人员不需要知道目标类基)
使用目标类的最专业包装器自动包装(因此库用户不需要知道目标类基础)
我对 C# 或C++解决方案感兴趣。不确定是否有模式可以在一个而不是另一个中轻松实现。
我假设您无法自行修改库,因此无法为每个类添加方法?
如果我理解正确,我认为您可以使用扩展方法。 在 C# 中,它会是这样的。
public static class FishExtension
{
public static void Print(this Fish fish)
{
// Now you can work with the fish object.
}
}
然后,鱼的使用者将能够做到:
Fish fish = new Fish();
fish.Print();
这样就没有额外的层次结构(没有包装器)中的扩展类从不直接使用,用户只需导入其命名空间。
请参阅扩展方法(C# 编程指南)https://msdn.microsoft.com/en-us//library/bb383977.aspx
相关文章:
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++ 将函数指针与最佳性能相结合
- 在指向现有内存地址的 hpp 文件中声明成员函数的最佳方法
- std::使用类成员函数创建线程 - 最佳实践
- 将(临时的?)std::string传递给使用它来构造一个接受副本的对象的函数的最佳方法是什么?
- 在 c++ 或 python 中生成一个体面的视差图以在 Raspberry Pi 上实现的最佳方法(算法或函数)是什么
- 将uint8_t*buffer和size_tbufferlen从C++传递到C中的API函数的最佳方式是什么
- 从类中的对象调用类中的函数的最佳方法
- 这是使用构造函数初始化数组对象的最佳方法吗?
- 最佳做法:在函数中频繁使用大时态缓冲区 (C++)
- 在 c++ 中抽象两个略有不同的函数的最佳方法是什么?
- C++最佳实践:接受uint8_t、uint16_t、uint32_t、浮点数的函数
- 使用 emplace_back 避免移动构造函数调用的最佳方法?
- 调用不属于基类的派生类函数的最佳方法是什么?
- C++最佳实践 - 函数类型别名 std::function<T> 或 T
- C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法
- 从C 中的函数中动态分配的缓冲区返回的最佳模式是什么?
- 字符传递给其他函数最佳实践