8.3 GOF设计模式二: 适配器模式 Adapter
GOF设计模式二: 适配器模式 Adapter
为中国市场生产的电器,到了美国,需要有一个转接器才能使用墙上的插座,这个转接 器的功能、原理?
复习单实例模式
SingleTon的三个关键点
1)私有的:构造函数
2)私有的:成员变量,记录这个单实例
3)公有的getter函数:没有实例时创建它;已有实例则返回 该实例
面向对象中的适配器 Object oriented adapters
Scenario: you have an existing software system that you need to work a new vendor library
into, but the new vendor designed their interfaces differently than the last vendor
What to do? Write a class that adapts the new vendor interface into the one you’re expecting.
The adapter implements the interface your classes expect
And talks to the vendor interface to service your requests
3.3 适配器模式 The Adapter Pattern Defined
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter l
ets classes work together that couldn’t otherwise because of incompatible interfaces
将一个类的接口转换成客户希望的另外一个接口, Adapter模式使原本由于接口不兼容而不能一起工作的那些类可以一起工作
Full of good OO design principles:多个好的OO设计原则
--Use of object composition 对象组合
--Pattern binds the client to an interface and not an implementation 客户面向接口而不是实现
3.5 The Adapter Pattern: Key Features
Intent
Match an existing object beyond your control to a particular interface
Problem
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a derivative of
an abstract class
Solution
The Adapter provides a wrapper with the desired interface
Participants and collaborators
The Adapter adapts the interface of an Adaptee to match that of the Adapter's Target (the class it derives from). This allows
the Client to use the Adaptee as if it were a type of Target
Consequences
The pattern allows for preexisting objects to fit into new class structures without being limited by their interfaces
Implementation
Contain the existing class in another class. Have the containing class match the required interface and call the methods of the
contained class
3.6 实现细节 Check list
两个角色 Identify the players
Adaptee:The Adapter adapts the interface of an Adaptee to match that of the Adapter‘s Target (the class it derives from)
Client:use the Adaptee as if it were a type of Target
标识客户需要用到的接口 Identify the interface that the client requires
设计一个“包装器”使得 Adaptee 符合客户的需要
adapter/wrapper 类里面必须要有一个 adaptee class的对象 (负责工作)
adapter/wrapper 负责“映射” 客户接口与 adaptee 的接口
client uses (is coupled to) the new interface
3.7 适配器小结 Summary
当现有的系统需要使用另一个类Adaptee的功能,而那个类的接 口又不符合现有的系统,就要使用适配器
When you need to use an existing class and its interface is not the one you need, use an adapter
适配器负责把Adaptee类的接口转换成客户类需要的格式,以完 成客户的工作
An adapter changes an interface into one a client expects
实现一个适配器的工作量取决于目标接口的规模
Implementing an adapter may require little work or a great deal of work depending on the size and complexity of the target interface