1. 程式人生 > 實用技巧 >C# 設計模式(8)橋接模式

C# 設計模式(8)橋接模式

橋接模式

1.解決多維度問題

2.變化封裝

程式碼實現:

組合 變化封裝類 減少子類的數量

手機系統橋接

namespace BridgePattern.Bridge
{
    public interface ISystem
    {
        public string GetSystem();
        public string GetVersion();
    }
    class IOS:ISystem
    {
        public string GetSystem()
        {
            return "IOS";
        }

        public string GetVersion()
        {
            return "14.1";
        }
    }
    public class SmartisanOS:ISystem
    {
        public string GetSystem()
        {
            return "Smartisan_OS";
        }

        public string GetVersion()
        {
            return "7.0";
        }
    }
}

手機品牌:

namespace BridgePattern
{
    public abstract class BasePhone
    {
        public ISystem PhoneSystem;
        public abstract void UseCall();
        public abstract void UseText();
    }
    public class Iphone:BasePhone
    {
        public override void UseCall()
        {
            Console.WriteLine($"Use {this.GetType().Name} {this.PhoneSystem.GetSystem()} {this.PhoneSystem.GetVersion()} Call Somebody");
        }

        public override void UseText()
        {
            Console.WriteLine($"Use {this.GetType().Name} {this.PhoneSystem.GetSystem()} {this.PhoneSystem.GetVersion()} Send Text to Somebody");
        }
    }
    public class Smartisan:BasePhone
    {
        public override void UseCall()
        {
            Console.WriteLine($"Use {this.GetType().Name} {this.PhoneSystem.GetSystem()} {this.PhoneSystem.GetVersion()} Call Somebody");
        }

        public override void UseText()
        {
            Console.WriteLine($"Use {this.GetType().Name} {this.PhoneSystem.GetSystem()} {this.PhoneSystem.GetVersion()} Send Text to Somebody");
        }
    }
}

程式碼呼叫:

    class Program
    {
        static void Main(string[] args)
        {
            ISystem iOS = new IOS();
            ISystem smartisanOS = new SmartisanOS();


            BasePhone iPhone = new Iphone();
            iPhone.PhoneSystem = iOS;
            iPhone.UseCall();
            iPhone.UseText();

            BasePhone smartisan = new Smartisan();
            smartisan.PhoneSystem = smartisanOS;
            smartisan.UseCall();
            smartisan.UseText();


            BasePhone iPhoneSmartisanOS = new Iphone();
            iPhoneSmartisanOS.PhoneSystem = smartisanOS;
            iPhoneSmartisanOS.UseCall();
            iPhoneSmartisanOS.UseText();

            BasePhone smartisanIOS = new Smartisan();
            smartisanIOS.PhoneSystem = iOS;
            smartisanIOS.UseCall();
            smartisanIOS.UseText();
        }
    }

結果: