在编写一个计算器程序时,可以将业务逻辑和显示分离,业务逻辑封装为一个类(封装);如果要新添加一种运算,可以先创建一个Operation的基类,然后各种运算从Operation类继承,并实现GetResult()虚函数,这时添加新的运算只需要派生一个新的类,即不需要之前的运算参与编译。如何让计算器知道我是希望使用哪种运算呢?应该考虑单独的类来做这个创造实例的过程,这就是工厂。创建一个OperationFactory类,传入参数,函数createOperate就可以实例化出合适的对象。
Java代码如下:
java" id="highlighter_905134">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
public class OperationFactory { public static abstract class Operation { private double _numberA = 0 ; private double _numberB = 0 ; public double get_numberA() { return _numberA; } public void set_numberA( double _numberA) { this ._numberA = _numberA; } public double get_numberB() { return _numberB; } public void set_numberB( double _numberB) { this ._numberB = _numberB; } abstract double GetResult(); // TODO Auto-generated constructor stub } public static class OperationAdd extends Operation { double GetResult() { double result = get_numberA() + get_numberB(); return result; } } public static class OperationSub extends Operation { double GetResult() { double result = get_numberA() - get_numberB(); return result; } } public static Operation createOperate(String operate){ Operation oper = null ; if (operate.equals( "+" )) { oper = new OperationAdd(); } else if (operate.equals( "-" )) { oper = new OperationSub(); } return oper; } public static void main(String[] args) { Operation oper; oper = OperationFactory.createOperate( "+" ); oper.set_numberA( 1 ); oper.set_numberB( 2 ); double result = oper.GetResult(); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。