1

好吧,我希望你能理解我。我有两个班,ABB是 的子类A。它们具有相同的公共方法和含义相同的东西,但 B 做了一些不同的事情,因此它具有仅使用自身的附加方法和属性。比方说,A 类实现了一个newFromWizard交互式创建对象的方法。我可以根据用户输入实现逻辑,以 A的方法创建对象 A或对象 B。newFromWizard我的意思是,我可以从 A 的方法创建 B 对象吗?或者我需要在其他地方实施?最好的方法是什么?在实践中,我可以。但是,它对 OOP 是正确的吗?

顺便说一句,如果这很重要,我正在使用 Smalltalk。

4

4 回答 4

2

Yes, this is a well-known pattern in OO. In the Objective-C Cocoa libraries you'll find it applied systematically, and is known as class clusters. The result is that the Cocoa libraries are much easier to understand than the equivalent c# or java ones. It allows the hiding of a inheritance hierarchy behind an abstract class that has class side creation methods that return subclasses.

于 2013-11-13T17:56:13.037 回答
1
public class A{

    public B method(){
        B b = new B();
        return b;
    }
}

class B extends A{

}

如果这就是你所说的,它是有效的。

于 2013-11-13T00:58:02.220 回答
0
于 2013-11-13T06:59:04.703 回答
0

I think you shouldn't worry too much about whether it is "clean OO" to return an instance of a subclass. It's being used and done so often because it is very helpful and makes your code very readable compared to somme kind of factories and stuff.

My biggest concern here would be that you should name your class method carefully. Don't use #new is probably the most important rule, but you should always use a name that already says: give me an instance of what is appropriate right now.

I'd say this is not limited to subclasses, such a method can even return objects that do not inherit from the class. In a dynamically typed language, this is okay. Remember, we're in a dynamically typed language, so as long as you have polymorphic interfaces, the class of an object is not really important to its users as long as it responds to your message sends...

于 2013-12-29T16:03:15.580 回答