Adapter(结构型模式——适配器模式)

适配:
不改变原有实现基础上,将原来不兼容的接口转为兼容的接口。

适配器模式
在这里插入图片描述
意图:
在这里插入图片描述
适配器有两种:对象适配器和类适配器
优先使用对象适配器
1、对象适配器
结构:
Adaptee是Adapter的字段
在这里插入图片描述
例子:
场景:通过ArrayList来实现Stack
Adapter:Stack(适配器)
Adaptee:ArrayList(被适配对象)

namespace AdapterMethod
{
    
    
    public interface IStack//客户期望的接口
    {
    
    
        void Push(object item);
        object Pop();
        object Peek();
    }

    //对象适配器
    //将ArrayList适配,改变接口为Stack
    public class Stack : IStack//Adapter,适配对象
    {
    
    
        private ArrayList list;//Adaptee,被适配的对象

        public Stack()
        {
    
    
            list = new ArrayList();
        }

        public void Push(object item)
        {
    
    
            list.Add(item);
        }

        public object Pop()
        {
    
    
            object pop = list[list.Count - 1];
            list.RemoveAt(list.Count-1);
            return pop;
        }

        public object Peek()
        {
    
    
            return list[list.Count - 1];
        }
    }

2、类适配器
结构
在这里插入图片描述
例子
场景:通过ArrayList来实现Stack

 public interface IStack//客户期望的接口
    {
    
    
        void Push(object item);
        object Pop();
        object Peek();
    }
//类适配器
public class Stack01 : ArrayList, IStack
{
    
    
    public void Push(object item)
    {
    
    
        this.Add(item);
    }

    public object Pop()
    {
    
    
        object pop = this[this.Count - 1];
        this.RemoveAt(this.Count - 1);
        return pop;
    }

    public object Peek()
    {
    
    
        return this[this.Count - 1];
    }
}

为什么优先使用对象适配器?
因为类适配器继承自原接口(ArrayList)和用户期望接口(IStack),这样这个类(Stack01)即可以用在原接口可用的位置,又可以用在用户期望接口可用的位置,这样违反了单一职责原则。

具体完整的例子
1、已存在的类

public class ExitingClass//已存在的类
    {
    
    
        public void SpecificRequst1()
        {
    
    
        }

        public void SpecificRequest2()
        {
    
    
        }
    }

2、新环境使用的接口

    interface ITarget//新环境使用的接口
    {
    
    
        void Requst();
    }

3、适配器

 class Adapter : ITarget
    {
    
    
        private ExitingClass adaptee;

        ExitingClass Adaptee()
        {
    
    
            return new ExitingClass();
        }

        public void Requst()
        {
    
    
            adaptee.SpecificRequest2();
            adaptee.SpecificRequst1();
        }
    }

4、使用

    class  MySystem
    {
    
    
        public void Process(ITarget target)
        {
    
    
        }
    }

要点
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_51565051/article/details/131517007