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


    一 何为工厂方法模式?(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方法,原来的画布将被新画布替换。

  • 相关阅读:
    linux学习(一)
    Linux学习(用户管理)
    anyproxy mac安装
    python mitmproxy 代理
    Js常用方法map, sort
    echarts常用配置项【持续更新】
    【转】moment js 使用
    js Cannot assign to read only property 'exports' of object '#<Object>' at Modul,import 与module.exports混用问题
    a标签跳转referer漏洞
    element ui rate评分组建使用
  • 原文地址:https://www.cnblogs.com/encoreMiao/p/5201045.html
Copyright © 2020-2023  润新知