溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

設(shè)計模式-橋接模式

發(fā)布時間:2020-07-15 11:16:45 來源:網(wǎng)絡(luò) 閱讀:316 作者:全嗲吉祥 欄目:編程語言
//職責
abstract class Command
    {
        public abstract int Run<T>(T t);
    }
    class Add : Command
    {
        public override int Run<T>(T t)
        {
            Console.WriteLine("add{0}",t.ToString());
            return 0;
        }
    }
    class Update : Command
    {
        public override int Run<T>(T t)
        {
            Console.WriteLine("update{0}", t.ToString());
            return 0;
        }
    }
    class Delete : Command
    {
        public override int Run<T>(T t)
        {
            Console.WriteLine("delete{0}", t.ToString());
            return 0;
        }
    }
        //實體類
        bstract class Entity
    {
        protected Command command;
        public void SetCommand(Command _command)
        {
            command = _command;
        }
        public abstract int Run();       
    }
    class User : Entity
    {
        public string name { get; set; }
        public int age { get; set; }

        public override int Run()
        {
            return command.Run(this);
        }        
    }

    class Manager : Entity
    {
        public string name { get; set; }
        public int age { get; set; }

        public override int Run()
        {
            return command.Run(this);
        }
    }
        //前端
        static void Main(string[] args)
        {            
            Command add = new Add();
            Command update = new Update();
            Command delete = new Delete();
            Entity user = new User();
            user.SetCommand(add);
            user.Run();
            user.SetCommand(update);
            user.Run();
            user.SetCommand(delete);
            user.Run();
            Console.ReadLine();
        }

總結(jié):DEMO不是很適合做橋接模式,但是完全實現(xiàn)了橋接模式。
橋接模式就是把抽象類和他的職責分離,重新把職責整個一個新的抽象,然后把職責注入到抽象類。
用到了聚合(合成)復(fù)用原則(能用聚合的盡量不要用繼承),符合單一,開閉原則。
優(yōu)點:避免了繼承類的無線擴大,并且擴展性增強。
缺點:對業(yè)務(wù)理解不到位,可能被錯誤運用,就像DEMO。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI