1. 多态概念
多态是面向对象程序设计(OOP)的一个重要特征,指同一个实体同时具有多种形式,即同一个对象,在不同时刻,代表的对象不一样,指的是对象的多种形态。
可以把不同的子类对象都当作父类来看,进而屏蔽不同子类对象之间的差异,写出通用的代码,做出通用的编程,统一调用标准。
多态的主要用途
1、提高程序的可扩展性;
2、降低系统耦合度;
3、提高系统的可维护性。
示例
结合大话设计模式,第9页-第11页的代码,通过简单工厂模式实现计算器小程序,深刻理解面向对象的多态。
Operation-运算类
public class Operation { private double _numberA = 0; private double _numberB = 0; public double NumberA { get { return _numberA; } set { _numberA = value; } } public double NumberB { get { return _numberB; } set { _numberB = value; } } public virtual double GetResult() { double result = 0; return result; } }
OperationFactory-简单运算工厂类
class OperationFactory { public static Operation createOperate(string operate) { Operation oper=null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper=new OperationSub(); break; case "*": oper=new OperationMul(); break; case "/": oper=new OperationDiv(); break; } return oper; } }
OperationAdd-加法类
class OperationAdd:Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } }
OperationSub-减法类
public class OperationSub:Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } }
OperationMul-乘法类
class OperationMul:Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } }
OperationDiv-除法类
class OperationDiv:Operation { public override double GetResult() { double result = 0; if (NumberB==0) { throw new Exception("除数不能为0."); } result = NumberA + NumberB; return result; } }
客户端代码
Operation oper; oper = OperationFactory.createOperate("+"); oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult(); Console.WriteLine(result);
根据代码可知,Operation类是父类,加减乘除是Operation的子类。在各个子类中重写了父类中的GetResult方法,对于父类的同一个方法,各个子类有不同的实现,符合多态的概念。