开发手册 欢迎您!
软件开发者资料库

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

设计模式(Design pattern)是代码设计经验的总结。设计模式主要分三个类型:创建型、结构型和行为型。创建型是对象实例化的模式,创建型模式用于解耦对象的实例化过程,主要用于创建对象。结构型是把类或对象结合在一起形成一个更大的结构,主要用于优化不同类、对象、接口之间的结构关系。行为型是类和对象如何交互,及划分责任和算法。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。本文主要介绍.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();        }    }}