解释器模式

定义

给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子

场景

  • 将一个需要解释执行的语言中的句子表示为一个抽象语法树
  • 一些重复出现的问题可以用一种简单的语言来进行表达
  • 一个简单语法需要解释的场景

实现

以100+10-20为例。
1、UML图


解释器模式.png

2、使用

  • 构建抽象解释器表达式类
@interface Expression : NSObject
-(int)interpret;
@end
#import "Expression.h"

@implementation Expression
- (int)interpret{
    NSLog(@"由具体的子类解释器实现");
    return 0;
}
@end
  • 构建具体解释器类
@interface PlusExpression : Expression
-(instancetype)initWithPlus:(Expression*)expression1 expression2:(Expression *)expression2;
@end
#import "PlusExpression.h"
@interface PlusExpression()
@property(nonatomic, strong)Expression *expression1;
@property(nonatomic, strong)Expression *expression2;
@end
@implementation PlusExpression
- (instancetype)initWithPlus:(Expression *)expression1 expression2:(Expression *)expression2
{
    self = [super init];
    if (self) {
        self.expression1 = expression1;
        self.expression2 = expression2;
    }
    return self;
}

- (int)interpret{
    return [self.expression1 interpret] + [self.expression2 interpret];
}
@end

@interface ValueExpression : Expression
-(instancetype)initWithValue:(int)value;
@end
#import "ValueExpression.h"
@interface ValueExpression()
@property(nonatomic, assign)int value;
@end
@implementation ValueExpression
- (instancetype)initWithValue:(int)value
{
    self = [super init];
    if (self) {
        self.value = value;
    }
    return self;
}
- (int)interpret{
    return self.value;
}
@end

@interface SubExpression : Expression
-(instancetype)initWithSub:(Expression *)expression1 expression2:(Expression *)expression2;
@end
#import "SubExpression.h"
@interface SubExpression()
@property(nonatomic, strong)Expression *expression1;
@property(nonatomic, strong)Expression *expression2;
@end
@implementation SubExpression
- (instancetype)initWithSub:(Expression *)expression1 expression2:(Expression *)expression2
{
    self = [super init];
    if (self) {
        self.expression2 = expression2;
        self.expression1 = expression1;
    }
    return self;
}

- (int)interpret{
    return [self.expression1 interpret] - [self.expression2 interpret];
}
@end
  • Client调用
    Expression *value1 = [[ValueExpression alloc] initWithValue:100];
    Expression *value2 = [[ValueExpression alloc] initWithValue:10];
    Expression *value3 = [[ValueExpression alloc] initWithValue:20];
    Expression *plus = [[PlusExpression alloc] initWithPlus:value1 expression2:value2];
    Expression *sub = [[SubExpression alloc] initWithSub:plus expression2:value3];
    NSLog(@"100+10-20=%d", [sub interpret]);

总结

该模式主要用于编译器、运算表达式计算

代码

链接: https://pan.baidu.com/s/1v3etJ-9X_Z1p3J3sEcLCzw 提取码: 6laq

你可能感兴趣的:(解释器模式)