当前:适配器模式
需求:坦克大战
创建两种坦克
坦克类型 | 射程 | 速度 |
b70 | 70米 | 时/70公里 |
b50 | 50米 | 时/70公里 |
类图
代码
interface IAFunction{
void execute();
}
interface ITank{
void execute();
void setmAFunction(IAFunction mAFunction);
}
interface IBFunction{
void operation();
}
class AFunction implements IAFunction{
public void execute() {
System.out.println("AFunction:炮弹发射");
}
}
class BFunction implements IBFunction{
public void operation() {
System.out.println("BFunction:炮弹发射");
}
}
class Tank implements ITank{
IAFunction mAFunction;
public void setmAFunction(IAFunction mAFunction) {
this.mAFunction = mAFunction;
}
public void execute() {
mAFunction.execute();
}
}
class Adapter implements IAFunction{
IBFunction mBFunction;
public Adapter(IBFunction fun) {
mBFunction = fun;
}
public void execute() {
mBFunction.operation();
}
}
class Adapter2 extends BFunction implements IAFunction{
public void execute() {
operation();
}
}
public class Client {
public static void main(String[] args) {
System.out.println("适配器演示");
ITank tank = new Tank();
//“建好了坦克本来打算装载IAFunction接口”
//“但是发现IAFunction接口的发射器没有了”
//“只有IBFunction接口的发射器
IBFunction ibfun = new BFunction();
//“怎么办,只有做实验适配器了,转载”
//“做个适配器装载IBFunction接口的发射器”
///*“1对象适配器”*///
System.out.println("对象适配器");
IAFunction adapter = new Adapter(ibfun);
tank.setmAFunction(adapter);
tank.execute();
///*“类适配器”*///
System.out.println("类适配器");
Adapter2 adapter2 = new Adapter2();
tank.setmAFunction(adapter);
tank.execute();
}
}
运行结果