• [结构型(接口型模式)]Adapter pattern 适配器模式


    1 Adapter模式的作用
        假设存在已经开发好的类及其特定方法,但是在reuse的时候和现有接口之间存在不协调,这时我们必须利用某种机制将已经存在的特定方法转化为另外能够接受的方法。这就是Adapter pattern。
    (Adapter pattern是所有模式中最简单直观的模式了 :) )
    2 Adapter模式的分类
        Adapter模式的实现分为2种方式。
        一种是建立一个inherented from Adaptee的类Adapter,当然由该类实现符合client要求的Target接口。因此,Adapter 和Adaptee之间是 is-a的关系。其类图如下所示:


        另外一种是在Adapter类中定义一个Adaptee类型的对象。通过借助Adaptee对象来实现Target接口内的方法。因此,Adapter和Adaptee之间是has-a的关系。其类图如下所示:

    3 代码实现:
         Is-a Adapter pattern implementation:
        public Interface Target
        {
            public void RequestMethod();
        }
        public class  Adaptee
        {
            public void ExistedMethod()
            {
                Console.WriteLine("this is a original method");
            }
        }

        public class Adatper:Target, Adaptee
        {
            public void RequestMethod()
            {    
            Console.Write("the method is modified");
            base.ExistedMethod();
            }
        }

        Has-a Adapter pattern implementation:
         public Interface Target
        {
            public void RequestMethod();
        }
        public class  Adaptee
        {
            public void ExistedMethod()
            {
                Console.WriteLine("this is a original method");
            }
        }

        public class Adatper:Target
        {
            protected Adaptee Adapteeobj;       
            public void RequestMethod()
            {    
                Adapteeobj=new Adaptee();       
                Adapteeobj.ExistedMethod(); 
            }
        }


  • 相关阅读:
    css3 过渡
    2021.1.5 算法实训
    表单 form
    表格 table
    Windows系统重装记录
    多线程【基础】
    关于excuteQuery与execute()
    关于jsp的action如何调用servlet的自定义方法
    selenium
    验证码处理
  • 原文地址:https://www.cnblogs.com/Winston/p/1195336.html
Copyright © 2020-2023  润新知