設計模式-橋接模式及使用場景


官方定義:

橋接模式是將抽象部分與它的實現部分分離,使它們都可以獨立地變化。它是一種對象結構型模式,又稱為柄體(Handle and Body)模式或接口(Interfce)模式。

最佳實踐:

如果一個系統需要在構建的抽象化角色和具體角色之間增加更多的靈活性,避免在兩個層次之間建立靜態的繼承關系,通過橋接模式可以使它們在抽象層建立一個關聯關系,抽象化角色和實現化角色可以獨立擴展而互不影響,在程序運行時可以動態的組合。
一個類存在兩個維度的變化,且這兩個維度都需要進行擴展

案例:

使用橋接模式將數據庫選擇的功能抽象出來,也就是上面說的抽象化角色(DB),DB和Repository之間有更多的靈活性,可以自由選擇、獨立擴展、互不影響,在程序運行時可以動態組合。
DB:包含IDbConnection,子類目前有MysqlDB、SqlServerDB,還可以擴展其他數據庫DB

客戶端:

            IDB orderDB = new MysqlDB("server=.;~~~~~~~");
            Order_masterRepository orderRepository = new Order_masterRepository(orderDB);
            var orderList = orderRepository.Select("SELECT * FROM Order_master");//從Mysql版的Order數據庫查找訂單


            IDB productDB = new SqlServerDB("server=.;~~~~~~~");
            ProductRepository productRepository = new ProductRepository(productDB);
            var productList = productRepository.Select("SELECT * FROM Product");//從Sqlserver版的Product數據庫查找產品

Model:

    public class Order_master
    {
        public int ID { get; set; }
        public decimal TotalPrice { get; set; }
    }
    public class Product
    {
        public int ID { get; set; }
        public string Title { get; set; }
    }

DB:

    public interface IDB
    {
        IDbConnection GetConnection();
    }
    public class MysqlDB : IDB
    {
        private string _connStr = null;
        public MysqlDB(string connStr)
        {
            _connStr = connStr;
        }
        public IDbConnection GetConnection()
        {
            return new MySqlConnection(_connStr);
        }
    }
    public class SqlServerDB : IDB
    {
        private string _connStr = null;
        public SqlServerDB(string connStr)
        {
            _connStr = connStr;
        }
        public IDbConnection GetConnection()
        {
            return new SqlConnection(_connStr);
        }
    }

Repository:

    public interface IRepository<T>
    {
        IEnumerable<T> Select(string sql);
    }
    public class Order_masterRepository : IRepository<Order_master>
    {
        private IDbConnection _connection = null;
        public Order_masterRepository(IDB db)
        {
            _connection = db.GetConnection();
        }
        public IEnumerable<Order_master> Select(string sql)
        {

            return _connection.Query<Order_master>(sql);
        }
    }
    public class ProductRepository : IRepository<Product>
    {
        private IDbConnection _connection = null;
        public ProductRepository(IDB db)
        {
            _connection = db.GetConnection();
        }
        public IEnumerable<Product> Select(string sql)
        {
            return _connection.Query<Product>(sql);
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM