首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Objective-C繼承與組合模式實戰教程

     編輯:關於C語言

Objective-C繼承與組合模式實戰教程

一、OC繼承語法

  • 單根繼承:一個類僅能有一個父類
  • 關鍵字:: 如 @interface Child : Parent
  • 繼承內容:父類所有方法 + 非private實例變量

示例:三角形類繼承

// 父類
@interface Triangle : NSObject
@property double a, b, c;
- (instancetype)initWithA:(double)a B:(double)b C:(double)c;
- (double)area;
@end

// 子類:無任何代碼,自動獲得父類所有能力
@interface TriangleSub : Triangle
@end

@implementation TriangleSub
@end

// 使用
TriangleSub *sub = [[TriangleSub alloc] initWithA:10 B:11 C:12];
double area = [sub area]; // 直接調用父類方法

二、OC動態特性

核心規則:方法調用根據對象實際內存類型(isa指針指向的類)決議,而非變量聲明類型。

驗證代碼

@interface TestClass : NSObject
- (void)test;
@end

@interface SubA : TestClass @end
@implementation SubA
- (void)test { NSLog(@"SubA test"); }
@end

@interface SubB : TestClass @end
@implementation SubB
- (void)test { NSLog(@"SubB test"); }
@end

// 測試
SubA *a = [[SubB alloc] init]; // 聲明SubA*,實際指向SubB對象
[a test]; // 輸出:"SubB test" —— 運行時根據實際類型調用

id關鍵字:編譯期不指定類型,運行時同樣動態分發,但失去IDE代碼提示。

三、組合模式

將其他對象作為自身部分(屬性),復用現成功能,而非繼承。

案例:組裝電腦

// SDK提供組件
@class Keyboard, Mouse, Monitor, CPU;

@interface Computer : NSObject
@property (strong, nonatomic) Keyboard *keyboard;
@property (strong, nonatomic) Mouse *mouse;
@property (strong, nonatomic) Monitor *monitor;
@property (strong, nonatomic) CPU *cpu;
@end

@implementation Computer
- (instancetype)init {
    self = [super init];
    if (self) {
        self.keyboard = [[Keyboard alloc] init];
        self.mouse = [[Mouse alloc] init];
        self.monitor = [[Monitor alloc] init];
        self.cpu = [[CPU alloc] init];
    }
    return self;
}
@end

屬性修飾符詳解

類別關鍵字說明
讀寫權限readwrite默認,可讀可寫
readonly只讀
內存管理assign默認,基本類型/弱引用
strong對象強引用(ARC下保留)
weak弱引用,對象釋放自動置nil
copy複製語義,常用NSString/Block
線程安全atomic默認,線程安全但較慢
nonatomic非原子,高性能,常用

四、super關鍵字與繼承組合協同

重寫父類方法時,super調用父類實現,避免完全覆蓋。

案例:高級空調(繼承基礎空調 + 組合除甲醛模塊)

// 基礎組件
@interface AirConditioner : NSObject
- (void)cooling; // 制冷
@end

@interface FormaldehydeRemover : NSObject
- (void)removeFormaldehyde; // 除甲醛
@end

// 高級空調
@interface AdvancedAC : AirConditioner
@property (strong, nonatomic) FormaldehydeRemover *remover;
@end

@implementation AdvancedAC
- (instancetype)init {
    self = [super init];
    if (self) self.remover = [[FormaldehydeRemover alloc] init];
    return self;
}

- (void)cooling {
    [super cooling];       // 1. 執行父類制冷邏輯
    [self.remover removeFormaldehyde]; // 2. 額外除甲醛
}
@end

總結

  • 繼承:is-a關系,獲取父類完整能力,慎用(耦合度高)
  • 組合:has-a關系,靈活復用,首選方案
  • super:繼承中擴展而非覆蓋父類行為的關鍵
  • 動態分發:運行時根據實際對象類型調用方法,是OC多態基石
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved