新彩天欢迎您!
幻海优品

.NET(C#) 设计模式 适配器模式

适配器模式(Adapter Pattern)

适配器模式(Adapter Pattern)也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。适配器模式是一种结构型模式,一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

1)类适配器模式

using System;namespace ConsoleApplication{    //目标接口    //现有的    interface ITarget    {        void request();    }    //用户所期待的    class Adaptee    {        public void specificRequest()        {            Console.WriteLine("适配者中的业务代码被调用!");        }    }    //类适配器类    class ClassAdapter : Adaptee, ITarget    {        public void request()        {            specificRequest();        }    }    //客户端代码    class Program    {        public static void Main(String[] args)        {            Console.WriteLine("类适配器模式测试:");            ITarget target = new ClassAdapter();            target.request();        }    }}

2)对象适配器模式

using System;namespace ConsoleApplication{    //目标接口    //现有的    interface ITarget    {        void request();    }    //用户所期待的    class Adaptee    {        public void specificRequest()        {            Console.WriteLine("适配者中的业务代码被调用!");        }    }    //对象适配器类    class ObjectAdapter : ITarget    {         private Adaptee adaptee;        public ObjectAdapter(Adaptee adaptee)        {            this.adaptee = adaptee;        }        public void request()        {            adaptee.specificRequest();        }    }    //客户端代码    class Program    {        public static void Main(String[] args)        {            Console.WriteLine("对象适配器模式测试:");            Adaptee adaptee = new Adaptee();            ITarget target = new ObjectAdapter(adaptee);            target.request();        }    }}

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除