c# 设计模式

一、简单工厂模式

即一样的产品包装(父类),不同的产品内容(子类)

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
        judge: //goto的标签,用法注意
            Console.WriteLine("请输入序号,1:宏基笔记本 2. 华为笔记本 3.戴尔笔记本");
            int printin = Convert.ToInt32( Console.ReadLine());
            Computer comp=null;  //声明的父类类型,应该调用父类自己的方法,但是因为被重载,所以调用的是子类的方法,即多态
            switch (printin)
            {
                //将所选择的子类装到父类里,利用多态,输出子类自己的方法
                case 1: comp = new Acer();
                    break;
                case 2:
                    comp = new Huawei();
                    break;
                case 3:
                    comp = new Acer();
                    break;
                default: Console.WriteLine("出错了!");
                    goto judge;
            }
            comp.OutDescripe();  //所装子类的方法
          
        }
    }
}
public abstract class Computer  //不需要实例化,用抽象类
{
    public abstract void OutDescripe();
}
public class Acer : Computer
{
    public override void OutDescripe()
    {
        Console.WriteLine("我是子类宏基笔记本");
    }
}

public class Huawei : Computer
{
    public override void OutDescripe()
    {
        Console.WriteLine("我是子类华为笔记本");
    }
}

public class DEll : Computer
{
    public override void OutDescripe()
    {
        Console.WriteLine("我是子类戴尔笔记本");
    }
}

  

 二、单例模式

用静态字段储存,废掉构造函数

FORM2:

public partial class Form2 : Form
    {
        //构造函数设为私有
       private Form2()
        {
            InitializeComponent();
        }
        
        //一个字段储存类,预设null

        private static Form2 f2 = null;
        public static Form2 F2 { get => f2; set => f2 = value; }
    
        //核心,判断是否是同一个
        public static Form2 Single()
        {
            if (F2==null)
            {
                F2=new Form2();
            }

            return f2;
        }

  form1中:

            Form2 f2 = Form2.Single();
            f2.Show();

  

 

posted @ 2021-04-05 00:19  遥月  阅读(92)  评论(0)    收藏  举报