### Behavioral Pattern
#### interpreter pattern
string -> code
instruction set: 提供基本操作
virtual machine: 执行指令
front-end: 生成效率更高的字节码
```
void setHealth(int wizard, int amount);
void setWisdom(int wizard, int amount);
void setAgility(int wizard, int amount);
void playSound(int soundId);
void spawnParticles(int particleType);
enum Instruction
{
INST_SET_HEALTH = 0x00,
INST_SET_WISDOM = 0x01,
INST_SET_AGILITY = 0x02,
INST_PLAY_SOUND = 0x03,
INST_SPAWN_PARTICLES = 0x04
};
switch (instruction)
{
case INST_SET_HEALTH:
setHealth(0, 100);
break;
case INST_SET_WISDOM:
setWisdom(0, 100);
break;
case INST_SET_AGILITY:
setAgility(0, 100);
break;
case INST_PLAY_SOUND:
playSound(SOUND_BANG);
break;
case INST_SPAWN_PARTICLES:
spawnParticles(PARTICLE_FLAME);
break;
}
### stack matchine
class VM
{
public:
VM()
: stackSize_(0)
{}
private:
void push(int value)
{
// Check for stack overflow.
assert(stackSize_ < MAX_STACK);
stack_[stackSize_++] = value;
}
int pop()
{
// Make sure the stack isn't empty.
assert(stackSize_ > 0);
return stack_[--stackSize_];
}
private:
static const int MAX_STACK = 128;
int stackSize_;
int stack_[MAX_STACK];
};
case INST_ADD:
{
int b = pop();
int a = pop();
push(a + b);
break;
}
```
### subclass 沙箱
子类使用父类提供的方法
#### Type Object
```
class Monster{}
class Drogon: Monster {}
class Troll: Monster {}
VS
class Breed {}
class Monster{
public Breed breed;
}
Monster drogon = new Monster{ breed= new Breed("drogon")};
Breed read config
// 好处
// monster的breed可以随便修改, 配置生成生物,不用重新编译代码
```