Adapter 如果客户需要使用某个类的服务,而这项服务是这个类用一个不同的接口提供的,那么,可以使用适配器模式为客户提供一个期望的接口...

it2022-05-09  30

类适配器:

客户程序定义好的接口 1using System;23namespace Gof.Test.adapter4{5    public interface ICart6    {7        void Driver();8    }9} 已经存在的类  1using System; 2 3namespace Gof.Test.adapter 4{ 5    public class AlreadyWrite 6    { 7        public AlreadyWrite() 8        { 9        }1011        public void DriverMyCart()12        {13            Console.WriteLine("AlreadyWrite is Drivering!");14        }15    }16} 类适配器  1using System; 2 3namespace Gof.Test.adapter 4{ 5    public class CartAdapetee:AlreadyWrite,ICart//先写类,后写接口。 6    { 7 8        public CartAdapetee() 9        {}1011        ICart 成员#region ICart 成员1213        public void Driver()14        {15            base.DriverMyCart();16        }1718        #endregion19    }20} 客户程序调用  1using System; 2 3namespace Gof.Test.adapter 4{ 5    public class Client 6    { 7        public Client() 8        { 9        }10        public void DriverCart()11        {12            ICart cart = new CartAdapetee();13            cart.Driver();14            Console.ReadLine();15        }16    }17} 对象适配器: 用户程序已经使用的类  1using System; 2 3namespace Gof.Test.adapter 4{ 5    public class CartUsed 6    { 7        public CartUsed() 8        { 9        }10        public virtual void DriverMyCart()11        {12            Console.WriteLine("I want to Drivering My Cart!");13        }14    }15}

客户程序通过把要适配的类标记为Virtula,使得我们有机会重载它。但这样做有可能存在风险。

客户程序  1using System; 2 3namespace Gof.Test.adapter 4{ 5    public class Client 6    { 7        public Client() 8        { } 9        public void DriverCart()10        {11            CartAdapeteeObj cart = new CartAdapeteeObj();12            cart.DriverMyCart();13            Console.ReadLine();14        }15    }16} 对象适配器  1using System; 2 3namespace Gof.Test.adapter 4{ 5    public class CartAdapeteeObj:CartUsed 6    { 7        private AlreadyWrite already; 8        public CartAdapeteeObj() 9        {10            already = new AlreadyWrite();11        }12        public override void DriverMyCart()13        {14            already.DriverMyCart();15        }                          16    }17} The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

转载于:https://www.cnblogs.com/nanshouyong326/archive/2007/01/04/611613.html


最新回复(0)