设计模式适配器模式Adapter.ppt
文本预览下载声明
设计模式(Design Pattern)
张凯 副教授
计算机学院 软件工程系
结构模式(Structural Pattern)
结构模式
结构模式(Structural Pattern)描述如何将类或者对象结合在一起形成更大的结构。结构模式描述两种不同的东西:类与类的实例(即对象)。 根据这一点,结构模式可以分为类的结构模式和对象的结构模式。
结构模式(Structural Pattern)
结构模式
适配器模式(Adapter)
桥接模式(Bridge)
组合模式(Composite)
装饰模式(Decorator)
外观模式(Facade)
享元模式(Flyweight)
代理模式(Proxy)
问题(Problem)
在NBA我需要翻译
姚明刚来到NBA,身材够高,球技够好
但是英语不是很懂,听不懂教练的战术安排
球员分为前锋、中锋和后卫
教练会给球员分配进攻、防守任务
问题(Problem)
问题(Problem)
火箭教练的指挥
Patrick Patterson, Attack(前锋 帕特里克-帕特森)
Terrence Williams, Attack(后卫 泰伦斯-威廉姆斯)
Yao Ming,Attack (中锋 姚明)
Attack?
要我干啥嘛?
主要内容
适配器模式(Adapter)
模式动机
模式名称:适配器模式(Adapter)
通常,客户类(client of class)通过类的接口访问它提供的服务。有时现有的类(existing class )可以提供客户类的功能需要,但是它所提供的接口不一定是客户类所期望的。这是由于现有的接口名称与客户类所查找的不同等诸多不同原因导致的。
适配器模式(Adapter)
模式动机
在这种情况下, 现有的接口需要转化 (convert) 为客户类期望的接口,这样保证了对现有类的重用。适配器模式(Adapter Pattern)可以完成这样的转化。
适配器模式(Adapter)
模式定义
适配器模式(Adapter Pattern): 将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。
适配器模式(Adapter)
模式结构
适配器模式(Adapter)
模式结构
适配器模式(Adapter)
参与者
Target:目标抽象类
Adapter:适配器类
Adaptee:适配者类(被适配)
Client:客户类
适配器模式(Adapter)
abstract class Player //篮球运动员
{
protected string name;
public Player(string name)
{
this.name = name;
}
public abstract void Attack();
public abstract void Defense();
}
class Forwards : Player //前锋
{
public Forwards(string name) : base(name)
{
}
public override void Attack()
{
Console.WriteLine(前锋 {0} 进攻, name);
}
public override void Defense()
{
Console.WriteLine(前锋 {0} 防守, name);
}
}
适配器模式(Adapter)
class ForeignCenter //外籍中锋
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public void 进攻()
{
Console.WriteLine(外籍中锋 {0} 进攻, name);
}
public void 防守()
{
显示全部