会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
我思考..我存在..
好好学习..天天向上.. 159753258 楼上我老婆,楼下是我! 呼叫中心、小型信息管理系统,电话:13516218837
博客园
首页
新随笔
联系
管理
订阅
Adapter 如果客户需要使用某个类的服务,而这项服务是这个类用一个不同的接口提供的,那么,可以使用适配器模式为客户提供一个期望的接口
类适配器:
客户程序定义好的接口
1
using
System;
2
3
namespace
Gof.Test.adapter
4
{
5
public
interface
ICart
6
{
7
void
Driver();
8
}
9
}
已经存在的类
1
using
System;
2
3
namespace
Gof.Test.adapter
4
{
5
public
class
AlreadyWrite
6
{
7
public
AlreadyWrite()
8
{
9
}
10
11
public
void
DriverMyCart()
12
{
13
Console.WriteLine(
"
AlreadyWrite is Drivering!
"
);
14
}
15
}
16
}
类适配器
1
using
System;
2
3
namespace
Gof.Test.adapter
4
{
5
public
class
CartAdapetee:AlreadyWrite,ICart
//
先写类,后写接口。
6
{
7
8
public
CartAdapetee()
9
{}
10
11
ICart 成员
#region
ICart 成员
12
13
public
void
Driver()
14
{
15
base
.DriverMyCart();
16
}
17
18
#endregion
19
}
20
}
客户程序调用
1
using
System;
2
3
namespace
Gof.Test.adapter
4
{
5
public
class
Client
6
{
7
public
Client()
8
{
9
}
10
public
void
DriverCart()
11
{
12
ICart cart
=
new
CartAdapetee();
13
cart.Driver();
14
Console.ReadLine();
15
}
16
}
17
}
对象适配器:
用户程序已经使用的类
1
using
System;
2
3
namespace
Gof.Test.adapter
4
{
5
public
class
CartUsed
6
{
7
public
CartUsed()
8
{
9
}
10
public
virtual
void
DriverMyCart()
11
{
12
Console.WriteLine(
"
I want to Drivering My Cart!
"
);
13
}
14
}
15
}
客户程序通过把要适配的类标记为Virtula,使得我们有机会重载它。但这样做有可能存在风险。
客户程序
1
using
System;
2
3
namespace
Gof.Test.adapter
4
{
5
public
class
Client
6
{
7
public
Client()
8
{ }
9
public
void
DriverCart()
10
{
11
CartAdapeteeObj cart
=
new
CartAdapeteeObj();
12
cart.DriverMyCart();
13
Console.ReadLine();
14
}
15
}
16
}
对象适配器
1
using
System;
2
3
namespace
Gof.Test.adapter
4
{
5
public
class
CartAdapeteeObj:CartUsed
6
{
7
private
AlreadyWrite already;
8
public
CartAdapeteeObj()
9
{
10
already
=
new
AlreadyWrite();
11
}
12
public
override
void
DriverMyCart()
13
{
14
already.DriverMyCart();
15
}
16
}
17
}
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
posted @
2007-01-04 17:26
南守拥
阅读(
289
) 评论(
1
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告