前面的文章介绍过如何使用鸿蒙布局功能构建一个计算器界面,本文是那篇文章的续集。使用作者以前学习安卓开发时写的一个计算器程序,后来出版《实战Python设计模式》一书时又将其作为解释器模式的例子进行说明。首先看基本动作的演示视频:

Calculator1

以下是主画面代码中和计算引擎相关的部分(全部代码可以参照文章最后的链接):

package com.xwg.harmonycalulator.slice;
public class MainAbilitySlice extends AbilitySlice {    static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbilitySlice");    private CalculateEngine calculator = null;    private boolean finished = false;    @Override    public void onStart(Intent intent) {        super.onStart(intent);        super.setUIContent(ResourceTable.Layout_ability_main);        HiLog.warn(label, "AbilitySlice onStart!");
        calculator = new CalculateEngine(getContext());        Button calculate_button = (Button)findComponentById(ResourceTable.Id_calucate_button);        calculate_button.setClickedListener(new Component.ClickedListener() {            public void onClick(Component v) {                calculate();            }        });    }
    private void appendQuestionString(String str){        TextField question = (TextField)findComponentById(ResourceTable.Id_question_field);        if(finished){            clearQuestion();            finished = false;        }        question.setText(question.getText() + str);    }
    private void clearQuestion(){        TextField question = (TextField)findComponentById(ResourceTable.Id_question_field);        question.setText("");        TextField answer = (TextField)findComponentById(ResourceTable.Id_answer_field);        answer.setText("0");    }}

代码第13行构建计算引擎,第14行~第19行为=按钮定义响应处理,其内容是调用下面的私有calculate方法。​​​​​​​

private void calculate(){        TextField questionField = (TextField)findComponentById(ResourceTable.Id_question_field);        TextField answerField = (TextField)findComponentById(ResourceTable.Id_answer_field);        try {            answerField.setText(calculator.calculate(questionField.getText(), false));        } catch (NotExistException | WrongTypeException | IOException e) {            e.printStackTrace();            answerField.setText("System Error");        }        finished = true;    }

代码中第5行,调用计算引擎的calculate方法,输入参数是输入的表达式,计算结果输出到结果TextField上:

参考资料

完整源代码已经上传至Github,读者可以根据需要从以下链接下载:

https://github/xueweiguo/Harmony

使用代码时,需要自行准备gradle模块。那个模块太大了。

有关计算引擎部分不是本系列文章的内容,具体实现可以参照下面的作者新书。虽然开发语言不同,但是无论是类结构还是实际的实现代码,基本都一样。

作者著作介绍

《实战Python设计模式》是作者去年3月份出版的技术书籍,该书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

更多推荐

自学鸿蒙应用开发(24)- 会计算的计算器(含源码)