设计模式(4)

适配器模式:把一个类的接口变换成客户端所期待的另一种接口(以两孔、三孔插座为例)
    类的适配器模式:
     public interface IThreeHole
    {
        void Request();
    }
    public abstract class TwoHole
    {
        public void SpecificRequest()
        {
            Console.WriteLine("我是两个孔的插头");
        }
    }
    /// <summary>
    /// 适配器类,接口要放在类的后面
    /// 适配器类提供了三个孔插头的行为,但其本质是调用两个孔插头的方法
    /// </summary>
    public class PowerAdapter:TwoHole,IThreeHole
    {
        /// <summary>
        /// 实现三个孔插头接口方法
        /// </summary>
        public void Request()
        {
            // 调用两个孔插头方法
            this.SpecificRequest();
        }
    }
    
    对象的适配器模式:
    public class ThreeHole
    {
        // 客户端需要的方法
        public virtual void Request()
        {
        }
    }
    public class TwoHole
    {
        public void SpecificRequest()
        {
            Console.WriteLine("我是两个孔的插头");
        }
    }
    /// <summary>
    /// 适配器类,这里适配器类没有TwoHole类,
    /// 而是引用了TwoHole对象,所以是对象的适配器模式的实现
    /// </summary>
    public class PowerAdapter : ThreeHole
    {
        public TwoHole twoholeAdaptee = new TwoHole();
        public override void Request()
        {
            twoholeAdaptee.SpecificRequest();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_34520411/article/details/82820081