A framework for defining an algorithm in an operation that delays steps to subclasses so that subclasses can redefine specific steps of an algorithm without changing the structure of the algorithm.

  • Such as answer the steps to do
    • 1. Fill in your name
    • 2. Answer the first question
    • 3. Answer the second question
    • 4. Complete the questions
  • Everyone is the same in Step 1 and Part 4, but everyone may have different answers to question 1 and question 2.
  • Essentially, the parent class defines a sequence of method steps to execute, and the subclass changes its own specific implementation by re-specifying the method.
  • To establish
#import <Foundation/Foundation.h> @interface HCDtextPaper : NSObject - (void)testPrepare; - (void)testQuestion1; - (NSString *)answer1; - (void)testQuestion2; - (NSString *)answer2; @end #import "hcdTextpaper. h" @implementation HCDtextPaper -(void)testPrepare{NSLog(@" fill in your name to prepare for answer "); Question: Yang Guo got it, and later gave it to Guo Jing. The black iron that was turned into tianjian and Dragon saber was probably [] : a. Ball mill cast iron B. tinplate C. high speed alloy steel D. carbon fiber "); NSLog(@" answer: %@", [self answer1]); } -(NSString *)answer1{ return nil; Question: Yang Guo, Cheng Ying, Lu Wushuang uprooted the love flower, causing [] : a. B. Make a rare species extinct. C. Disturb the ecological balance of that biosphere. Desertification of the region "); NSLog(@" answer: %@", [self answer2]); } -(NSString *)answer2{ return nil; } - (void)dealloc{NSLog(@" complete answer "); } @endCopy the code
#import "HCDtextPaper.h" @interface HCDtextPaperA : HCDtextPaper @end #import "HCDtextPaperA.h" @implementation HCDtextPaperA - (instancetype)init { self = [super init]; if (self) { [self testPrepare]; } return self; } - (void)testPrepare{ NSLog(@"A"); [super testPrepare]; NSLog(@" Draw a heart on your name "); } -(NSString *)answer1{ return @"b"; } -(NSString *)answer2{ return @"c"; } @endCopy the code
#import "HCDtextPaper.h"

@interface HCDtextPaperB : HCDtextPaper

@end

#import "HCDtextPaperB.h"

@implementation HCDtextPaperB
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self testPrepare];
    }
    return self;
}

-(NSString *)answer1{
    return @"a";
}
-(NSString *)answer2{
    return @"d";
}
@end

Copy the code
  • call
#import "ViewController.h"
#import "HCDtextPaper.h"
#import "HCDtextPaperA.h"
#import "HCDtextPaperB.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    HCDtextPaper *paperA = [[HCDtextPaperA alloc]init];
    [paperA testQuestion1];
    [paperA testQuestion2];
    
    HCDtextPaper *paperB = [[HCDtextPaperB alloc]init];
    [paperB testQuestion1];
    [paperB testQuestion2];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Copy the code