隐藏实现细节

241 阅读1分钟

类比UIButton的创建,创建按钮时:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

按钮类型枚举:

typedef NS_ENUM(NSInteger, UIButtonType) {
     UIButtonTypeCustom = 0,                         // no button type
     UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),  // standard system button
     
     UIButtonTypeDetailDisclosure,
     UIButtonTypeInfoLight,
     UIButtonTypeInfoDark,
     UIButtonTypeContactAdd,
     
     UIButtonTypeRoundedRect = UIButtonTypeSystem,   // Deprecated, use UIButtonTypeSystem instead
     };

我们来类比UIButton

屏幕快照 2017-04-07 15.03.19.png

Test:

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSUInteger, CaiTestType) {
    TestTypeOne,
    TestTypeTwo,
    TestTypeThree
};

@interface Test : NSObject

+ (Test *)createTest:(CaiTestType)type;

- (void)doSomething;

@end



#import "Test.h"
#import "TestOne.h"
#import "TestTwo.h"
#import "TestThree.h"

@implementation Test

+ (Test *)createTest:(CaiTestType)type
{
    switch (type) {
        case TestTypeOne:
            return [TestOne new];
            break;
        case TestTypeTwo:
            return [TestTwo new];
            break;
        case TestTypeThree:
            return [TestThree new];
            break;
        default:
            break;
    }
}

- (void)doSomething
{
    //子类实现
}

@end

TestOne TestTwo TestThree

#import "TestOne.h"

@implementation TestOne

- (void)doSomething
{
    NSLog(@"---TestOne doSomething");
}

@end


#import "TestTwo.h"

@implementation TestTwo

- (void)doSomething
{
    NSLog(@"---TestTwo doSomething");
}

@end


#import "TestThree.h"

@implementation TestThree

- (void)doSomething
{
    NSLog(@"---TestThree doSomething");
}

@end


ViewController

#import "ViewController.h"
#import "Test.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor orangeColor];
    
    Test *testOne = [Test createTest:TestTypeOne];
    [testOne doSomething];
    
    Test *testTwo = [Test createTest:TestTypeTwo];
    [testTwo doSomething];
    
    Test *testThree = [Test createTest:TestTypeThree];
    [testThree doSomething];
    
    Test *test = [Test createTest:TestTypeThree];
    [test doSomething];
}

@end

打印结果:

2017-04-07 15:01:39.293 Test[58960:2605033] ---TestOne doSomething
2017-04-07 15:01:39.293 Test[58960:2605033] ---TestTwo doSomething
2017-04-07 15:01:39.293 Test[58960:2605033] ---TestThree doSomething
2017-04-07 15:01:39.294 Test[58960:2605033] ---TestThree doSomething