如何在初始化父类时返回子类的新实例? [英] How to return new instance of subclass while initializing parent class?

查看:155
本文介绍了如何在初始化父类时返回子类的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定类层次结构如下:

  class A 
def initialize param)
如果param == 1则
#initialize并返回B的实例
else
#initialize并返回C
的实例end
end
end

class B< A
end

class C< A
end

是否可以实际初始化并返回<​​$ c $当初始化 A 时,是否为 B 或 C ?也就是说 my_obj = A.new(param)会导致 my_obj 成为 B param 的值 C 在我的usecase它唯一已知在运行时,其中的子类( B



C ),而父类( A )基本上从未真正使用过。
我认为移动决定 B C 的逻辑是一个好主意共同祖先。



如果这是不可能的(或不好的风格),我应该把 param 和决定哪个类初始化

解决方案

你打破了一个基本的OO原则 - 子类。当然,有时候原则应该被打破,但没有明显的理由在这里。



一个更好的解决方案是将实例化逻辑转换为单独类中的工厂方法。工厂方法使用与上述A的初始化器相同的参数,并返回适当类的实例。


Given a class hierarchy as follows:

class A
  def initialize(param)
    if param == 1 then
      #initialize and return instance of B
    else
      #initialize and return instance of C
    end
  end
end

class B < A
end

class C < A
end

Is it possible to actually initialize and return an instance of B or C when initializing A? I.e. my_obj = A.new(param) would result in my_obj being an instance of class B or C depending on the value of param, which gets checked in A.initialize(param).

In my usecase its only known at runtime which subclass (B or C) to use and the parent class (A) is basically never really used. I thought it might be a good idea to move the logic of deciding whether B or C into their common ancestor.

If this is not possible (or bad style), where should I put the check of param and the decision which class to initialize?

解决方案

You're breaking a fundamental OO principle here -- classes should know nothing about their subclasses. Of course, sometimes principles should be broken, but there's no apparent reason to do it here.

A far better solution is to shift the instantiation logic to a factory method in a separate class. The factory method takes the same arguments as the A's initializer above, and returns an instance of the appropriate class.

这篇关于如何在初始化父类时返回子类的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆