之前了解一些设计模式,只是粗略的了解到设计模式的名称,对各种设计模式并不懂。听闻说大话设计模式这本书不错,近来下载其电子版以学之,初读第一章,无事以记之。
对于一个简单的计算器我们该如何设计,能达到面向对象的特点,达到最优的设计。面向对象的设计思想,通过封装、继承、多态把程序的耦合度降低,用设计模式使程序更加的灵活,容易修改,并且易于复用。计算器设计结构图如下:
用java实现代码如下:
运算类
public class Operation { private double numberA; private double numberB; public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } public double getResult() throws Exception { return 0; }}
加减乘除类
public class OperationAdd extends Operation { public double getResult() { return getNumberA() + getNumberB(); }}
public class OperationSub extends Operation {
public double getResult() { return getNumberA() - getNumberB(); }}
public class OperationMul extends Operation {
public double getResult() { return getNumberA() * getNumberB(); }}
public class OperationDiv extends Operation {
public double getResult() throws Exception { if (getNumberB() == 0) { throw new Exception("除数不能为零"); } return getNumberA() / getNumberB(); }}
简单的工厂类
public class OperationFactory {
public static Operation createOperate(char operate) { Operation op = null; switch (operate) { case '+': op = new OperationAdd(); break; case '-': op = new OperationSub(); break; case '*': op = new OperationMul(); break; case '/': op = new OperationDiv(); break; } return op; }}
测试类,简单客户端了,呵呵
public class Calculator {
public static void main(String[] args) { Operation op; op = OperationFactory.createOperate('+'); op.setNumberA(1); op.setNumberB(2); double result; try { result = op.getResult(); System.out.print(result); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
以后就是我学习工厂模式的一点笔记,有错的地方,请大家指正。