6.适配器模式

来源:互联网 发布:union在sql中的意思 编辑:程序博客网 时间:2024/06/15 18:48

介绍

由于应用环境的变化(例如使用语言的变化),我们需要的实现在新的环境中没有现存对象可以满足,但是其他环境却存在这样现存的对象。那么如果将“将现存的对象”在新的环境中进行调用呢?使得新环境中不需要去重复实现已经存在了的实现而很好地把现有对象(指原来环境中的现有对象)加入到新环境来使用。

核心要点

“把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法一起工作的两个类能够在一起工作”

例子

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 适配器模式{    class Target    {        public virtual void Request()        {            Console.WriteLine("Called Target Request");        }    }    class Adapter:Target    {        private Adaptee adaptee = new Adaptee();        public override void Request()        {            //Todo something            adaptee.SpecificRequest();        }    }    class Adaptee    {        public void SpecificRequest()        {            Console.WriteLine("Called SpecificRequest");        }    }} //使用方法using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 适配器模式{    class Program    {        static void Main(string[] args)        {            Target target = new Adapter();            target.Request();            Console.ReadKey();        }    }}

例子:二转换为三箱插头,将高电压转换为低电压等

原创粉丝点击