模板模式
定义一个类,继承该抽象类,重写抽象方法,通过调用抽象类,实现对子类的调用
UML
Java
- 实现抽象类:
public abstract class AbstractCalculator { /*主方法,实现对本类其它方法的调用*/ public final int calculate(String exp, String opt) { int array[] = split(exp, opt); return calculate(array[0], array[1]); } /*被子类重写的方法*/ abstract public int calculate(int num1, int num2); public int[] split(String exp, String opt) { String array[] = exp.split(opt); int arrayInt[] = new int[2]; arrayInt[0] = Integer.parseInt(array[0]); arrayInt[1] = Integer.parseInt(array[1]); return arrayInt; } }
- 子类继承抽象类,实现抽象方法:
public class Plus extends AbstractCalculator { @Override public int calculate(int num1, int num2) { return num1 + num2; } }
- 测试类:
public class PlusTest { public static void main(String[] args) { String exp = "2+8"; AbstractCalculator cal = new Plus(); int result = cal.calculate(exp, "\\+"); System.out.println(result); } }
- 测试结果:
10
CLOS
- 使用通用方法:
(defclass calculator () () ) (defclass plus (calculator) ()) (defclass minus (calculator) ()) (defclass multiply (calculator) ()) (defmethod calculate ((p plus) op1 op2) (+ op1 op2)) (defmethod calculate ((m minus) op1 op2) (- op1 op2)) (defmethod calculate ((m multiply) op1 op2) (* op1 op2))
- 测试结果:
(calculate (make-instance 'plus) 8 2) ;; => 10 (calculate (make-instance 'minus) 8 2) ;; => 6 (calculate (make-instance 'multiply) 8 2) ;; => 16