适用于预先存在的 class 层次结构的函数的最佳模式

Best pattern for functions that apply to a preexisting class hierarchy

我有一个现有的 class 层次结构,我无法修改

即系统发育树:

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 映射目标层次结构的包装器层次结构。每个包装器实现它自己的功能,即:

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++ 解决方案感兴趣。不确定是否存在可以在一个而不是另一个中轻松实现的模式。

我假设您无法自行修改库,因此您无法向每个库添加方法 class?

如果我理解正确,我认为您可以使用扩展方法。在 C# 中它会是这样的。

public static class FishExtension
{
    public static void Print(this Fish fish)
    {
     // Now you can work with the fish object.
    }
}   

fish 的用户将能够做到:

Fish fish = new Fish();
fish.Print();

这样就没有额外的层次结构(没有包装器) 扩展 class 从未直接使用,用户只需导入其命名空间。

参见扩展方法(C# 编程指南) https://msdn.microsoft.com/en-us//library/bb383977.aspx