OC编程之道-创建对象之工厂方法

时间:2024-01-03 21:31:26

一 何为工厂方法模式?(what)

定义创建对象的接口,让子类决定实例化哪一个类,工厂方法是的一个类的实例化延迟到其子类。

工厂方法创建的对象拥有一组共同的行为,所以往类层次结构中引入新的具体产品并不需要修改客户端代码。

二 何时使用工厂方法?(where)

编译时期无法准确预期要创建的对象的类。

eg:[NSNumber numberWithBool:YES];工厂方法模式对框架设计者特别有用。

三 实现工厂方法 (how)

CanvasView定义了任意CanvasView类型的默认行为。其子类用不同图像在屏幕上展现各种纹理并展现其他可能的特定行为。

PaperCanvasView:CanvasView

方法:

- (id)initWithFrame:(CGRect)frame

{

  if(self == [super initWithFrame:frame])

  {

    UIImage *backgroundImage = [UIImage imageNamed:@"paper"];

    UIImageView *backgroundView =[[[UIImageView alloc]initWithImage:backgroundImage]autorelease];

    [self addSubview:backgroundView];

  }

  return self;

}

ClothCanvasView:CanvasView

方法:

- (id)initWithFrame:(CGRect)frame

{

  if(self == [super initWithFrame:frame])

  {

    UIImage *backgroundImage = [UIImage imageNamed:@"cloth"];

    UIImageView *backgroundView =[[[UIImageView alloc]initWithImage:backgroundImage]autorelease];

    [self addSubview:backgroundView];

  }

  return self;

}

CanvasViewGenerator生成器默认方法返回舞团的CanvasView

CanvasViewGenerator:NSObject

- (CanvasView *)canvasViewWithFrame:(CGRect)aFrame

{

  return [[[CanvasView alloc]initWithFrame:aFrame]autorelease];

}

PaperCanvasViewGenerator:CanvasViewGenerator

- (CanvasView *)canvasViewWithFrame:(CGRect)aFrame

{

  return [[[PaperCanvasView alloc]initWithFrame:aFrame]autorelease];

}

ClothCanvasViewGenerator:CanvasViewGenerator

- (CanvasView *)canvasViewWithFrame:(CGRect)aFrame

{

  return [[[ClothCanvasView alloc]initWithFrame:aFrame]autorelease];

}

CanvasViewController现在使用原来的CanvasView为了在 运行时加一改变,则在CanvasViewController中添加一个方法,通过CanvasViewGenerator取得CanvasView的实例。

- (void)viewDidLoad

{

  [super viewDidLoad];

  CanvasViewGenerator *defaultGenerator =[[[CanvasViewGenerator alloc]init]autorelease];

  [self loadCanvasViewWithGenerator:defaultGenerator];

}

- (void)loadCanvasViewWithGenerator:(CanvasViewGenerator *)generator

{

  [CanvasView_ removeFromSuperView];

  CGRect aFrame = CGReckMake(0,0,320,436);

  CanvasView *aCanvasView = [generator canvasViewWithFrame:aFrame];

  [self setCanvasView:aCanvasView];

  [[self view] addSubview:canvasView_];

}

以上,当选择特定的画布类型时,应用程序会把具体生成器的实例传给loadCanvasViewWithGenerator方法,原来的画布将被新画布替换。