天天看點

擴充卡模式

擴充卡模式:将一個類的接口變換成用戶端所期待的另一種接口,進而使原本因接口不比對而無法在一起工作的兩個類能夠在一起工作。

場景:你有動機修改一個已經投産中的接口時,擴充卡模式可能是最适合你的模式。

UML圖:

擴充卡模式
示例代碼:

public interface ITarget
    {
        void Request();
    }      
public class Source
    {
        public void OtherRequest()
        {
            Console.WriteLine("邏輯處理");
        }
    }      
public class Adapter:Source, ITarget
    {
        public void Request()
        {
            this.OtherRequest();
        }
    }      
class Program
    {
        static void Main(string[] args)
        {
            LuoJi(new Adapter());//如果存在SourceA,SourceB,處理方式類似
        }

        static void LuoJi(ITarget target)
        {
            target.Request();
        }
    }