标签: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