2017年1月2日 星期一

設計模式 Simple Factory 簡單工廠模式

情境:
要設計一個連接資料庫的物件,提供 MSSQL 與 MYSQL 兩種連線方式
讓使用者使用

 1.首先定一個介面
  1. public interface IDBConnection
  2. {
  3. void GetIDBConnection();
  4. }
  5.  
2.實作 MYSQL 與 MSSQL 資料庫連線方式
  1. public class MSSQL : IDBConnection
  2. {
  3. public void GetDBConnection()
  4. {
  5. Console.WriteLine("MYSQL連線 ");
  6. }
  7. }
  8. public class MYSQL:IDBConnection
  9. {
  10. public void GetDBConnection()
  11. {
  12. Console.WriteLine("MYSQL 連線");
  13. }
  14. }
  15.  
3.實做工廠類別
  1.  
  2. public class ConnectionFactory
  3. {
  4. public static IDDConnection GetConnection(DBType type)
  5. {
  6. IDDConnection db_ = null;
  7. switch (type)
  8. {
  9. case DBType.MySQL:
  10. db_ = new MYSQL();
  11. break;
  12. case DBType.MSSQL:
  13. db_ = new MSSQL();
  14. break;
  15. default:
  16. Console.WriteLine("default type");
  17. break;
  18. }
  19. return db_ ;
  20. }
  21. }
  22.  
  23.  
4.外部使用簡單工廠模式
  1.  
  2. class Program
  3. {
  4. static void Main(string[] args)
  5. {
  6. IDBConnection Connection_ = ConnectionFactory.GetConnection(DBType.MySQL);
  7. Connection.GetDBConnection();
  8. Console.ReadKey();
  9. }
  10. }
  11.  
  12.  

沒有留言:

Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD