Table of contents
What is polymorphism?
Concept: Polymorphism means that the same operation acts on different objects, which can have different interpretations and produce different execution results. To put it simply: it is to use the reference of the base class to point to the object of the subclass.
Why polymorphism?
first. To understand the three major characteristics of object-oriented, one encapsulation can hide the specific details of the implementation, making the code modular; the second inheritance can extend the existing code modules (classes); their purpose is to - code reuse. In addition to the reusability of the code, its three polymorphisms can also solve the problem of tight coupling in the project and improve the scalability of the program. The degree of coupling refers to the degree of correlation between modules and codes. Through the analysis of the system, it is decomposed into sub-modules. The sub-modules provide stable interfaces to reduce the coupling degree of the system. Modules Try to use the module interface to access, rather than randomly refer to the member variables of other modules.
implement polymorphism
Operation class
public class Operation
{
private double _numberA = 0;
private double _numberB = 0;
/// 数字A
public double NumberA
{
get
{
return _numberA;
}
set
{
_numberA = value;
}
}
/// 数字B
public double NumberB
{
get
{
return _numberB;
}
set
{
_numberB = value;
}
}
/// 得到运算结果
public virtual double GetResult()
{
double result = 0;
return result;
}
Addition class
class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
Subtraction class
class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
simple factory class
public class OperationFactory
{
public static Operation createOperate(string operate)
{
Operation oper = null;
switch (operate)
{
case "+":
{
oper = new OperationAdd();
break;
}
case "-":
{
oper = new OperationSub();
break;
}
}
return oper;
}
}
client
static void Main(string[] args)
{
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
Console.WriteLine(result);
}
self understanding
Polymorphism not only improves code reusability, but also greatly improves scalability, and complies with the principle of opening and closing.