Design Pattern【5】适配器模式
2010-08-12 13:03
141 查看
参考/article/5134059.html
将一个类的接口转换成客户期望的另一个接口。
适配器让原本不兼容的类可以合作无间。
当要使用一个现的类而其接口冻符合你的需要时,就使用适配器。
你可能会经常遇到下面这种情况,厂家提供的接口和你写的接口合不上,怎么办??
这时候你不想改变自己的接口来适应厂家的接口,同时你又不能改变厂家的接口,那么这个时候你就应该考虑使用适配器模式了。
厂家调用他们的接口,而实际上我们给的却是看似像厂家的接口的接口。
代码
我的例子:
我们都知道,在C#与SQL数据库连接的时候,可能要处理不同的事情总要连接不同的表,但是数据库是固定的。换句话说,在SQL的属性连接中,SqlConnection语句是不会发生变化的,变化的只是SqlCommand的值,因此我们使用的时候,就可以不需要每次都重写SQLConnection和SQLCommand代码,而增加一个接口和适配器,用来更新SqlCommand 的值即可
将一个类的接口转换成客户期望的另一个接口。
适配器让原本不兼容的类可以合作无间。
当要使用一个现的类而其接口冻符合你的需要时,就使用适配器。
你可能会经常遇到下面这种情况,厂家提供的接口和你写的接口合不上,怎么办??
这时候你不想改变自己的接口来适应厂家的接口,同时你又不能改变厂家的接口,那么这个时候你就应该考虑使用适配器模式了。
厂家调用他们的接口,而实际上我们给的却是看似像厂家的接口的接口。
代码
1 namespace 适配器模式 2 { 3 /// <summary> 4 /// 红色火鸡(我们的实现) 5 /// </summary> 6 public class RedTurkey : ITurkey 7 { 8 9 public void Giggling() 10 { 11 Console.WriteLine("发出声音!"); 12 } 13 14 public void Fly() 15 { 16 Console.WriteLine("在飞行!"); 17 } 18 } 19 } 20
1 namespace 适配器模式 2 { 3 /// <summary> 4 /// 适配器(把火鸡伪装成鸭子) 5 /// </summary> 6 public class TurkeyAdapter : IDuck 7 { 8 public TurkeyAdapter(ITurkey turkey) 9 { 10 this.Turkey = turkey; 11 } 12 13 ITurkey Turkey { get; set; } 14 15 public void Rattle() 16 { 17 Turkey.Giggling(); 18 } 19 20 public void Fly() 21 { 22 Turkey.Fly(); 23 } 24 } 25 }
我的例子:
我们都知道,在C#与SQL数据库连接的时候,可能要处理不同的事情总要连接不同的表,但是数据库是固定的。换句话说,在SQL的属性连接中,SqlConnection语句是不会发生变化的,变化的只是SqlCommand的值,因此我们使用的时候,就可以不需要每次都重写SQLConnection和SQLCommand代码,而增加一个接口和适配器,用来更新SqlCommand 的值即可
//厂家“接口” namespace WindowsFormsApplication6 { class SQL { public string comtest = ""; public void sql() { SqlConnection testcon = new SqlConnection(); testcon.ConnectionString = ""; testcon.Open(); SqlCommand testcom = new SqlCommand("",testcon); testcom.CommandText = comtest; } } }
//适配器 namespace WindowsFormsApplication6 { class adapter:SQL,Isetcom { public void setcommnad(string s) { comtest = s; } } }
//客户端的实现“接口” namespace WindowsFormsApplication6 { public interface Isetcom { void setcommnad(string s); } public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void client() { adapter ad = new adapter(); ad.setcommnad("newcomtest"); ad.sql(); } } }
相关文章推荐
- Design Pattern之适配器模式
- 设计模式学习—适配器模式(Adapter Design Pattern)
- Design Pattern:适配器模式
- java之适配器模式
- 抽象工厂模式 AbstractFactory---Design Pattern 2
- 跟我学设计模式视频教程——适配器模式,适配器模式VS装饰模式
- C++设计模式之适配器模式(三)
- php 设计模式之 代理模式,适配器模式,外观模式
- 结构模式之适配器模式(缺省适配器)
- 适配器模式(PHP实现)
- 【结构型模式一】适配器模式(Adapter)
- 装饰者模式,代理模式与适配器模式的比较
- 设计模式C++实现三——适配器模式
- 一个示例让你明白适配器模式
- 【设计模式】适配器模式
- 设计模式:适配器模式
- 设计模式--适配器模式Adapter
- 设计模式学习笔记十四:适配器模式、桥接模式与外观模式
- 我所理解的设计模式(C++实现)——适配器模式(Adapter Pattern)
- 设计模式之----------适配器模式