码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式二(简单工厂模式)

时间:2017-11-16 18:33:18      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:getc   tco   public   客户端   sharp   har   抽象类   cas   ring   

学习笔记之设计模式二,简单工厂;

假设要取得数据库连接字符串,

1.创建抽象类:

public abstract class ConnectString
{
        //输出字符串  
        public abstract string GetConnectString();
}

2.创建各个实体类:

    public class SqlConnectString : ConnectString
    {
        public override string GetConnectString()
        {
            return "SQL ConnectString";
            //throw new NotImplementedException();
        }
    }

    public class MySqlConnectString : ConnectString
    {
        public override string GetConnectString()
        {
            return "MySql ConnectString";
            //throw new NotImplementedException();
        }
    }

3.创建简单工厂类

    public class SimpleFactory
    {
        /// <summary>
        /// 静态方法创建Product实例
        /// </summary>
        public static ConnectString CreatConnectString(string dbtype)
        {
            ConnectString connect = null;
            switch(dbtype)
            {
                case "MySql":
                    connect = new MySqlConnectString();
                    break;
                case "SqlServer":
                    connect = new SqlConnectString();
                    break;
            }
            return connect;
        }
    }

4.客户端调用

        static void Main(string[] args)
        {
            ConnectString connectString = SimpleFactory.CreatConnectString("MySql");
            Console.WriteLine(connectString.GetConnectString());

            ConnectString connectString2 = SimpleFactory.CreatConnectString("SqlServer");
            Console.WriteLine(connectString2.GetConnectString());

            Console.Read();
        }

  

设计模式二(简单工厂模式)

标签:getc   tco   public   客户端   sharp   har   抽象类   cas   ring   

原文地址:http://www.cnblogs.com/yizhituoxie/p/7845308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!