工厂模式:

给予指令生产一个对象  返回类型为父类类型,

例子:

计算器功能:

public class JiSuan

    {

        private int a;

 

        public int A

        {

            get { return a; }

            set { a = value; }

        }

        private int b;

 

        public int B

        {

            get { return b; }

            set { b = value; }

        }

 

 

        public virtual int YunSuan()

        {

            return 0;

        }

 

    }

 

    //加法类

    public class Jia:JiSuan

    {

        public override int YunSuan()

        {

            return base.A + base.B;

        }

    }

 

    //减法类

    public class Jian : JiSuan

    {

        public override int YunSuan()

        {

            return base.A - base.B;

        }

    }

 

 

    //工厂类

    public class GongChang

    {

        public static JiSuan DuiXiang(string s)

        {

            switch(s)

            {

                case "+":

                    return new Jia();

                    break;

                case "-":

                    return new Jian();

                    break;

                case "*":

                    return new Cheng();

                    break;

                default:

                    return new Jia();

                    break;

 

调用:

class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("请输入第一个数:");

            int a = Convert.ToInt32(Console.ReadLine());

 

            Console.WriteLine("请输入第二个数:");

            int b = Convert.ToInt32(Console.ReadLine());

 

       

            JiSuan c = GongChang.DuiXiang("-");

            c.A = a;

            c.B = b;

 

            Console.WriteLine("两个数的积为:"+c.YunSuan());

            Console.ReadLine();

 

          单例模式:

          控制一个类,只能实例化一个对象

例:

 

    //单列模式

    //控制一个类只能实例化一个对象

 

    class Test

    {

        public string name;

    }

 

    //数据访问类

    class DBDA

    {

        public string host;

        public string database;

 

        //静态成员,用来存储该类的对象

        public static DBDA db = null;

 

        //让该类不能被实例化

        private DBDA()

        {

        }

 

        //提供一个造对象的方法,控制只能造一个对象

        public static DBDA DuiXiang()

        {

            if (db == null)

            {

                db = new DBDA();

            }

 

            return db;

        }

    }

posted on 2016-08-11 16:17  Lovetolaugh  阅读(178)  评论(0编辑  收藏  举报