简单工厂和单例设计模式

一:设计模式 

概念:

针对特定问题而提出特定的解决方案

二:简单工厂

eg:

使用多态和简单工厂设计模式实现计算器,效果如图所示:

复制代码
   //父类
    public abstract class Operation
    {
        public double NumberA { get; set; }

        public double NumberB { get; set; }

        public abstract double GetResult();
}

     //子类 加法
    public class OperationAdd:Operation
    {
     
       public override double GetResult()
       {
           double result = NumberA + NumberB;
           return result;
       }
}

      //子类 减法
 public class OperationJian:Operation
    {
        public override double GetResult()
        {
            double result = NumberA - NumberB;
            return result;
        }

    }

   //子类 乘法
  public class OperationCheng:Operation
    {

       public override double GetResult()
       {
           double result = NumberA * NumberB;
           return result;
       }

    }

     //子类 除法
    public  class OperationChu:Operation
    {
       public override double GetResult()
       {
           if (NumberB == 0)
           {
               throw new Exception("除数不能为0!");
           }
           double result = NumberA / NumberB;
           return result;
       
       }
    }
复制代码

在计算按钮中获取两个操作数以及运算符、计算的方法

复制代码
  //获取两个操作数
            int num1 = Convert.ToInt32(txtList1.Text);

            int num2 = Convert.ToInt32(txtList2.Text);

            //获取运算符
            string oper = cboList.Text;

            Operation calc=OperationFactory.CreateInstance(oper);

            calc.NumberA = num1;
            calc.NumberB = num2;

            //计算方法
            int result = 0;

            try
            {
                result = Convert.ToInt32(calc.GetResult());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                throw;
            }

           label1.Text = result.ToString();
复制代码

工厂类:(核心 )

三:单例模式

单例模式要求一个类只能有一个对象

四步骤:

①:定义一个类型和当前类名相同的静态变量

②:将构造改为私有

③:定义一个静态方法  给静态变量赋值,实例化对象并返回实例引用

④:将静态变量置空

复制代码
     public partial class Form1 : Form
    {
        //定义一个类型和当前类名相同的静态变量
        public static Form1 frm;

        //将构造改成私有
       private Form1()
        {
            InitializeComponent();
        }

        //定义一个静态方法  给静态变量赋值
       public static Form1 GetInstance()
       {
           if (frm == null)
           { 
              frm=new Form1();
           }
           return frm;
       }


        //将静态变量置空
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            frm = null;
        }
复制代码
原文地址:https://www.cnblogs.com/hr1997/p/5392743.html