经验不多的程序员写程序喜欢按计算机思考的方式来进行编程,但是这样写出来的程序往往可维护性差,可拓展性不高,并且不容易复用代码,那么如何让写出来的代码能容易维护可拓展性好并且能够复用,这就需要面向对象的思维和方法。
书中用活字印刷形象地展示了面向对象的妙处,其一,之前的刻板印刷,更改一篇文章就需要更换一块刻板重新刻字,而活字印刷只需要“更改要改之字”,体现了可维护性;其二,一篇文章印刷完毕后,其活字印刷仍可复用到印刷其它文章,体现了复用性;其三,如果文章需要加字,增加对应的刻字即可,体现了可扩展性;其四,排版可竖排或横排,体现了灵活性。
使用面向对象的分析设计编程思想,通过封装、继承、多态把程序的耦合性降低,应用设计模式则可以使得程序更加灵活,容易修改并且复用性高。
编程是一门技术更是一门艺术,编写出优雅的代码是一件很爽的事情。
书中用一个编写计算器的例子体现了简单工厂模式比没有应用设计模式只按计算机思考方式编程的好处,在这个例子中,对运算逻辑进行封装(Operation类),然后继承这个封装类可以拓展不用的运算符运算类,如加法运算类OperationAdd等,然后写一个运算工厂类OperationFactory,这个OperationFactory类实现创建不用的运算方法createOperat,这样在前台就根据传入的运算符参数进行创建相应的运算类,使用该类的计算方法得到结果。
相关代码如下:

Code
using System;
using System.Collections.Generic;
using System.Text;
namespace OperationLibrary
{
public class Operation
{
private double _firstStr;
private double _secondStr;
public double FirstStr
{
set { _firstStr = value; }
get { return _firstStr; }
}
public double SecondStr
{
get { return _secondStr; }
set { _secondStr = value; }
}
public virtual double getResult()
{
double result = 0.0;
return result;
}
}
class OperationAdd : Operation
{
public override double getResult()
{
double result = 0.0;
result = FirstStr + SecondStr;
return result;
}
}
class OperationSub : Operation
{
public override double getResult()
{
double result = 0.0;
result = FirstStr - SecondStr;
return result;
}
}
class OperationMul : Operation
{
public override double getResult()
{
double result = 0.0;
result = FirstStr * SecondStr;
return result;
}
}
class OperationDiv : Operation
{
public override double getResult()
{
double result = 0.0;
if (SecondStr == 0)
throw new Exception("除数不能为0哦。");
result = FirstStr / SecondStr;
return result;
}
}
public class OperationFactory
{
public static Operation createOperat(string operate)
{
Operation operation = null;
switch (operate)
{
case "+":
operation = new OperationAdd();
break;
case "-":
operation = new OperationSub();
break;
case "*":
operation = new OperationMul();
break;
case "/":
operation = new OperationDiv();
break;
}
return operation;
}
}
}

Code
using System;
using System.Collections.Generic;
using System.Text;
using OperationLibrary;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("请输入第一个运算数字:");
string firstStr = Console.ReadLine();
Console.WriteLine("请输入第二个运算数字:");
string secondStr = Console.ReadLine();
Console.WriteLine("请输入运算符“+”或“-”或“*”或“/”:");
string operatorStr = Console.ReadLine();
Operation opr;
opr = OperationFactory.createOperat(operatorStr);
opr.FirstStr = Convert.ToDouble(firstStr);
opr.SecondStr = Convert.ToDouble(secondStr);
Console.WriteLine("计算结果是:" + opr.getResult());
}
catch (Exception ex)
{
Console.WriteLine("您的输入有错:"+ex.Message);
}
Console.ReadLine();
}
}
}