您的位置:首页 > 其它

Design Pattern【5】适配器模式

2010-08-12 13:03 141 查看
参考/article/5134059.html

将一个类的接口转换成客户期望的另一个接口。
适配器让原本不兼容的类可以合作无间。
当要使用一个现的类而其接口冻符合你的需要时,就使用适配器。

你可能会经常遇到下面这种情况,厂家提供的接口和你写的接口合不上,怎么办??

这时候你不想改变自己的接口来适应厂家的接口,同时你又不能改变厂家的接口,那么这个时候你就应该考虑使用适配器模式了。

厂家调用他们的接口,而实际上我们给的却是看似像厂家的接口的接口。

代码

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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: