您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 設計模式:抽象工廠模式的實作

編輯:iOS 開發綜合

設計模式是程式功力向上提升的必備知識。本文示範如何在 Objective-C 中實作抽象工廠模式,靈感來自《Objective-C 程式設計之道》的抽象工廠一章,若對原理不清楚,建議先讀過該章再回頭看程式碼。

抽象工廠的精神是:呼叫端只認得抽象產品與抽象工廠,實際產生哪個系列的產品由具體工廠決定,呼叫端完全不依賴實作細節。下面用一個產生自訂檢視的工廠來說明。

步驟一:建立產品類別

TestView.h

#import <UIKit/UIKit.h>

@interface TestView : UIView
@end

TestView.m

#import "TestView.h"

@implementation TestView

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor redColor];
    }
    return self;
}

@end

步驟二:建立抽象工廠與具體工廠

接著建立 TestBrandingFactory 作為抽象工廠,並讓 TestFactory 繼承它成為具體工廠。

TestBrandingFactory.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface TestBrandingFactory : NSObject

+ (TestBrandingFactory *)factory;
- (UIView *)createTestView:(CGRect)frame;

@end

TestBrandingFactory.m

#import "TestBrandingFactory.h"
#import "TestFactory.h"

@implementation TestBrandingFactory

// 抽象工廠的類別方法固定回傳具體工廠實例
+ (TestBrandingFactory *)factory {
    return [[TestFactory alloc] init];
}

// 抽象方法,預設不做任何事,交由子類別覆寫
- (UIView *)createTestView:(CGRect)frame {
    return nil;
}

@end

TestFactory.h

#import "TestBrandingFactory.h"

@interface TestFactory : TestBrandingFactory
@end

TestFactory.m

#import "TestFactory.h"
#import "TestView.h"

@implementation TestFactory

- (UIView *)createTestView:(CGRect)frame {
    return [[TestView alloc] initWithFrame:frame];
}

@end

步驟三:呼叫端使用

TestBrandingFactory *tmp = [TestBrandingFactory factory];
UIView *v = [tmp createTestView:CGRectMake(50, 110, 100, 50)];
[self.view addSubview:v];

呼叫端手上只有抽象型別 TestBrandingFactory,卻能拿到由 TestFactory 產出的 TestView 實例。未來若要換成另一個產品系列(例如換主題、換品牌風格),只需新增一組具體工廠與產品,呼叫端一行都不用改——這正是抽象工廠降低耦合的價值所在。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved