当前位置:
文档之家› 适配器(Adaptor)模式PPT教学课件
适配器(Adaptor)模式PPT教学课件
public double getMass(){ } public double getThrust(){ } public void setSimTime(double time){this.time=time;} }
2020/12/10
7
类适配器简单例子
public interface Print { public abstract void printWeak(); public abstract void printStrong();
} }
2020/12/10
9
对象适配器
Client
RequiredClass ______________ requiredMethod()
ExistingClass __________ usefulMethod()
} ============================ public class Main {
public static void main(String[] args) { Print p = new PrintBanner("Hello"); p.printWeak(); p.printStrong();
2020/12/10
4
Adapter模式
Struct
class adapter
object adapter
2020/12/10
5
例子
《interface》
RocketSim getMass():double getThrust():double setSimTime(t:double)
PhysicalRocket
} -------------------------public class Banner {
private String string; public Banner(String string) {
this.string = string; } public void showWithParen() {
OozimozRocket
2020/12/10
6
public class OozinozRocket extends PhysicalRocket implements RocketSim{ private double time;
Public OozinozRocket(double burnArea,double burnRate,double fuelMass,double totalMass){ super(burnArea,burnRate,fuelMass,totalMass); }
2
2020/12/10
3
Adapter模式
Applicability:Use the Adapter pattern when you want to use an existing class, and its interface does not match the one you need. 你想使用一个已经存在的类,并且它的接口不符合要求。
you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces.
PhysicalRocket( burnArea:double, burnRae:double, fueMass:double, totalMass:double) getBurnTime():double getMass(t:double):double getThrust(t:double):double
你想创建一个可以复用的类,该类可以与其他不相关的类或不 可预见的类(即那些接口可能不兼容的类)协同工作。
(object adapter only) you need to use several existing subclasses, but it‘s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.你想使用一些已经存在的子类,但 是不可能对每一个都进行子类化以匹配它们的接口。对象适配 器可以适配它们的父类接口。
假设有一图形编辑器,允许用接口:Shape,定义了图形对 象的基本接口服务。程序中所有图元对象均实 现该接口。
假设需要设计一个TextShape类,用来显示和 编辑正文。设计该类时希望用到现成的 TextView类,用来显示和编辑正文。
2020/12/10
适配器(Adaptor)模式
目的: 把一个已有的类用用户希望的形式描述;即用
用户希望的接口适配这个类。 在这个模式中,这个类叫做被适配者
(Adaptee),用户定义的接口叫适配接口, 用户实现适配接口的类叫适配器(Adaptor)。 也叫做,包装器(Wrapper)。
2020/12/10
1
Adapter
System.out.println("(" + string + ")"); } public void showWithAster() {
System.out.println("*" + string + "*"); } }
2020/12/10
8
public class PrintBanner extends Banner implements Print { public PrintBanner(String string) { super(string); } public void printWeak() { showWithParen(); } public void printStrong() { showWithAster(); }