本文介绍了iPhone-抽象类的初始化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建具有以下属性的汽车,车辆和飞机类:

I want to create classes Car, Vehicle, and Airplane with the following properties:


  • 汽车和飞机都是Vehicle的子类。

  • 汽车和飞机都具有initWithString方法。

  • 汽车和飞机的initWithString方法可接受的输入字符串不重叠。

  • 车辆是几乎抽象的,从某种意义上说,任何初始化的实例都应该是汽车或飞机。

  • 可以将字符串传递给Vehicle和根据输入字符串返回Car实例,飞机实例或nil实例。

  • 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.

任何特殊的设计模式我都应该喜欢吗?特别是对于Vehicle的initWithString和/或newVehicleWithString方法。

Any particular design pattern I should prefer? In particular for Vehicle's initWithString and/or newVehicleWithString methods.

推荐答案

您需要的是类集群模式。您的 Vehicle initWithString:方法可能类似于:

What you need is the "class cluster" pattern. Your Vehicle initWithString: method could look something like this:

- (id) initWithString:(NSString *)mode {
  // note that we don't call [super init] in a class cluster. 
  // instead, we have to release self because it's an unwanted Vehicle instance
  [self release];
  if([mode isEqualToString:@"wheels"]) {
    return [[Car alloc] initWithString:@"wheels"];
  }
  if([mode isEqualToString:@"wings"]) {
    return [[Airplane alloc] initWithString:@"wings"];
  }
  return nil;  //alternately, raise NSInvalidArgumentException
}

这篇关于iPhone-抽象类的初始化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 07:56