package com.example.shipeiqi;
public interface ThreeElectricOutlet
{
//用来刻画三相插座
public abstract void connectElectricCurrent();
}
package com.example.shipeiqi;
public class TreeElecricAdapter implements ThreeElectricOutlet
{
TwoElectricOutlet outlet;
public TreeElecricAdapter(
TwoElectricOutlet teo )
{
this.outlet = teo;
}
@Override
public void connectElectricCurrent()
{
outlet.connectElectricCurrent();
}
}
package com.example.shipeiqi;
public interface TwoElectricOutlet
{
//刻画两相插座
public abstract void connectElectricCurrent();
}
package com.example.shipeiqi;
public class Tv implements TwoElectricOutlet
{
private String name;
public Tv()
{
name = "长江电视机";
}
public Tv(
String s )
{
this.name = s;
}
@Override
public void connectElectricCurrent()
{
turnOn();
}
private void turnOn()
{
System.out.println( name + "开始播放节目" );
}
}
package com.example.shipeiqi;
public class Wash implements ThreeElectricOutlet
{
private String name;
public Wash()
{
name = "洗衣机";
}
public Wash(
String name )
{
this.name = name;
}
@Override
public void connectElectricCurrent()
{
turnOn();
}
private void turnOn()
{
System.out.println( name + "开始洗衣服" );
}
}
package com.example.shipeiqi;
/**
* 适配器模式示例
* 适配器一共包括3种角色
1、目标:目标是一个接口,该接口是客户想使用的接口
2、被适配者:被适配者是一个已存在的接口或抽象类,这个接口或抽象类需要适配
3、适配器:适配器是一个类,该类实现了目标接口并包含有被适配者的引用,即适配者的指着是对被适配者接口与目标进行适配
* @author Administrator
*
*/
public class TestActivity
{
public static void main(
String[] args )
{
ThreeElectricOutlet outlet;
Wash wash = new Wash();
outlet = wash;
outlet.connectElectricCurrent();
Tv tv = new Tv();
TreeElecricAdapter adapter = new TreeElecricAdapter( tv );
outlet = adapter;
outlet.connectElectricCurrent();
}
}
洗衣机开始洗衣服
长江电视机开始播放节目