Java 之 23 种设计模式解析——23、解释器模式(Interpreter)

23、解释器模式(Interpreter)

解释器模式是我们暂时的最后一讲,一般主要应用在OOP开发中的编译器的开发中,所以适用面比较窄。

 

Context类是一个上下文环境类,Plus和Minus分别是用来计算的实现,代码如下:

1. public interface Expression {
2.	public int interpret(Context context);
3.	}	
1. public class Plus implements Expression {
2.
3.	@Override
4.	public int interpret(Context context) {
5.	return context.getNum1()+context.getNum2();
6.		}
7.	}	
1. public class Minus implements Expression {
2.
3.	@Override
4.	public int interpret(Context context) {
5.	return context.getNum1()-context.getNum2();
6.		}
7.	}	

 

1. public class Context {
2.
3.	private int num1;
4.	private int num2;
5.
6.	public Context(int num1, int num2) {
7.	this.num1 = num1;
8.	this.num2 = num2;
9.	}	
10.
11.	public int getNum1() {
12.	return num1;
13.	}
14.	public void setNum1(int num1) {
15.	this.num1 = num1;
16.	}
17.	public int getNum2() {
18.	return num2;
19.	}
20.	public void setNum2(int num2) {
21.	this.num2 = num2;
22.	}
23. }
1. public class Test {
2.
3.	public static void main(String[] args) {
4.
5.		// 计算 9+2-8 的值
6.	int result = new Minus().interpret((new Context(new Plus()
7.	.interpret(new Context(9, 2)), 8)));
8.	System.out.println(result);
9.	}	
10. }

 最后输出正确的结果:3。

基本就这样,解释器模式用来做各种各样的解释器,如正则表达式等的解释器等等!

目录:(点击进入相应页面)

概述、六大原则

一、创建模式

0、简单工厂模式

1.工厂方法模式(Factory Method)

2、抽象工厂模式

3、单例模式(Singleton)

4、建造者模式(Builder)

5、原型模式(Prototype)

二、结构模式(7种)

6、适配器模式

7、装饰模式(Decorator)

8、代理模式(Proxy)

9、外观模式(Facade)

10、桥接模式(Bridge)

11、组合模式(Composite

12、享元模式(Flyweight)

三、关系模式(11种)

13、策略模式(strategy)

14、模板方法模式(Template Method)

15、观察者模式(Observer)

16、迭代子模式(Iterator)

17、责任链模式(Chain of Responsibility)

18、命令模式(Command)

19、备忘录模式(Memento

20、状态模式(State)

21、访问者模式(Visitor)

22、中介者模式(Mediator)

23、解释器模式(Interpreter)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值