1、定义一个Worker接口
<span style="font-size:18px;">interface Worker
{
void doSomeWork();
}</span>
2、定义一个水管工类Plumber
<span style="font-size:18px;">class Plumber implements Worker
{
public void doSomeWork()
{
System.out.println("修水管");
}
}</span>
3、定义一个木匠Canpenter
class Canpenter implements Worker
{
public void doSomeWork()
{
System.out.println("修门窗");
}
}
4、A公司,都要说你好
class AWorker implements Worker
{
private Worker worker;
AWorker(Worker worker)
{
this.worker = worker;
}
public void doSomeWork()
{
System.out.println("你好");
worker.doSomeWork();
}
}
5、测试
class TestWorker
{
public static void main(String args [])
{
Canpenter canpenter = new Canpenter();
AWorker aworker1 = new AWorker(canpenter);
aworker1.doSomeWork();
Plumber plumber = new Plumber();
AWorker aworker2 = new AWorker(plumber);
aworker2.doSomeWork();
}
}