电の岁月---点滴记忆
交流,分享,进步

参考http://www.cnblogs.com/homezzm/archive/2009/12/08/1619116.html

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

 

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

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

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

 

namespace 适配器模式
{
/// <summary>
/// 鸭子接口(厂家提供的接口)
/// </summary>
public interface IDuck
{
/// <summary>
/// 嘎嘎叫
/// </summary>
void Rattle();

/// <summary>
/// 飞行
/// </summary>
void Fly();

}
}

 

namespace 适配器模式
2 {
3 /// <summary>
4 /// 火鸡(被适配的接口)
5 /// </summary>
6 public interface ITurkey
7 {
8 /// <summary>
9 /// 咯咯叫
10 /// </summary>
11 void Giggling();
12
13 /// <summary>
14 /// 飞行
15 /// </summary>
16 void Fly();
17 }
18 }

 

1 namespace 适配器模式
2 {
3 /// <summary>
4 /// 绿毛鸭子(客户的实现)
5 /// </summary>
6 public class GreenDuck : IDuck
7 {
8 public void Rattle()
9 {
10 Console.WriteLine("发出声音!");
11 }
12
13 public void Fly()
14 {
15 Console.WriteLine("在飞行!");
16 }
17 }
18 }
19

 

代码
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();
}
}
}

 

posted on 2010-08-12 13:03  doucontorl  阅读(168)  评论(0编辑  收藏  举报