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

Best pattern for functions that apply to a preexisting class hierarchy

本文关键字:函数 最佳 模式 层次结构 存在 适用于      更新时间:2023-10-16

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

即系统发育树:

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

相关文章: