iPhone——抽象类的init方法
我想创建具有以下属性的汽车、车辆和飞机类:
- 汽车和飞机都是车辆的子类。
- 汽车和飞机都有一个 initWithString 方法。
- 汽车和飞机的 initWithString 方法可接受的输入字符串不重叠。
- 车辆是“几乎抽象的”,因为任何初始化的实例都应该是汽车或飞机。
- 可以将字符串传递到 Vehicle 并返回 Car 实例、Airplane 实例或 nil,具体取决于输入字符串。
我应该更喜欢什么特定的设计模式?特别是对于 Vehicle 的 initWithString 和/或 newVehicleWithString 方法。
I want to create classes Car, Vehicle, and Airplane with the following properties:
- Car and Airplane are both subclasses of Vehicle.
- Car and Airplane both have an initWithString method.
- The acceptable input strings for Car's and Airplane's initWithString methods do not overlap.
- Vehicle is "almost abstract", in the sense that any initialized instance should be either a Car or an Airplane.
- It is possible to pass a string into Vehicle and get back an instance of Car, an instance of Airplane, or nil, depending on the input string.
Any particular design pattern I should prefer? In particular for Vehicle's initWithString and/or newVehicleWithString methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要的是“类簇”模式。您的
Vehicle initWithString:
方法可能如下所示:What you need is the "class cluster" pattern. Your
Vehicle initWithString:
method could look something like this:从超类引用子类并不是一个好主意。
如果您确实必须这样做,您至少应该使用像
vehicleWithString:
这样的类方法。事实上,我怀疑另一种方法(使用
vehicle initWithString:
来创建汽车或飞机的实例)是否有效。Referring to a subclass from a superclass is not a good idea.
If you really have to do this, you should at least go with a class method like
vehicleWithString:
.In fact, I doubt that the other approach (using
vehicle initWithString:
to create instances of Car or Airplane) would work.