zoukankan      html  css  js  c++  java
  • iPhone开发重构:提供辅助创建方法以简化实例创建【转】

         无论在iPhone开发还是学习的过程中都会看到一些不是很理想的代码,不可否认自己也在不断“贡献”着这类代码。面对一些代码的“坏味道”,重构显然是 个有效的解决途径。《iPhone开发重构》系列就想总结和补充iPhone开发中经历的一些重构,其间可能会引用一些开源以及实际项目的代码,本着对技 术的探求,冒昧之处还请作者多多见谅。

        使用Objective-C的人应该都很熟悉通过alloc和init进行对象的“两阶段”创建。其实利用new的一次创建也是可以的,但由于“两阶段” 创建所具备的灵活性使得其成为了Objective-C创建对象的一种惯例。但真正使用的时候,开发人员有时更倾向与一些创建的辅助方法。比如 NSArray的arrayWithObjects以及arrayWithContentsOfFile等等。为此在类的接口设计时候考虑到友好性最好可 以提供一些更为简单的创建函数来封装“两阶段”的细节以及内存处理。借用下SoundEffect库的代码举例说明下:

    重构前:

    @implementation SoundEffect

    // Initializes a sound effect object with the contents of the specified sound file
    - (id)initWithContentsOfFile:(NSString *)path {
        self = [super init];
        // Gets the file located at the specified path.
        if (self != nil) {
            NSURL *aFileURL = [NSURL fileURLWithPath:path isDirectory:NO];
            // If the file exists, calls Core Audio to create a system sound ID.
            if (aFileURL != nil)  {
                SystemSoundID aSoundID;
                OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)aFileURL, &aSoundID);
                if (error == kAudioServicesNoError) { // success
                    _soundID = aSoundID;
                } else {
                    NSLog(@"Error %d loading sound at path: %@", error, path);
                    [self release], self = nil;
                }
            } else {
                NSLog(@"NSURL is nil for path: %@", path);
                [self release], self = nil;
            }
        }
        return self;
    }
    @end

    重构后:

    @implementation SoundEffect

    + (id)soundEffectWithContentsOfFile:(NSString *)aPath {
        if (aPath) {
            return [[[SoundEffect alloc] initWithContentsOfFile:aPath] autorelease];
        }
        return nil;
    }


    - (id)initWithContentsOfFile:(NSString *)path {
       ……
    }
    @end

       其中,重构前的代码是我假想的,重构后的代码才是SoundEffect库现有的模样。经过重构后,SoundEffect类在创建时的友好性得到了很大的改善。

    本文出自 “林家男孩” 博客,请务必保留此出处http://bj007.blog.51cto.com/1701577/545536

  • 相关阅读:
    c++析构函数、虚析构函数、纯虚析构函数详解
    php实现设计模式之 策略模式
    php实现设计模式之 简单工厂模式
    记录一下工作中碰到的一些有用的命令
    预估高并发下API服务器数量
    囧啊!!时间戳转化为时间出错php
    php 实现hash表
    php 中使用cURL发送get/post请求,上传图片,批处理
    redis虚拟内存
    redis主从同步
  • 原文地址:https://www.cnblogs.com/simonshi2012/p/2269343.html
Copyright © 2011-2022 走看看