Re: Could you comment on my little program? What design pattern it
is?
Thank you for your comments. Now see something new I did in the Class
MyHouse. The chair is broken. To fix it, write a class implementing
Talent interface, plug it into Expert. Now the Expert with Talent of
RepairingFurniture (a carpenter actually) is in my house now.
Expert.server() will fix the broken chair.
<code>
interface Talent
{
void showTalent();
}
class Singing implements Talent
{
public void showTalent()
{
System.out.println("do-rei-mei");
}
}
class Painting implements Talent
{
public void showTalent()
{
System.out.println("yellow, blue, red");
}
}
class Cooking implements Talent
{
public void showTalent()
{
System.out.println("gong-bao chicken");
}
}
class Expert
{
private Talent myTalent = null;
public Expert(Talent t)
{
myTalent = t;
}
public void serve()
{
myTalent.showTalent();
}
public static void main(String[] args)
{
Expert anExpert = new Expert(new Singing()); //this expert is singer
anExpert.serve();
anExpert = new Expert(new Cooking()); //this expert is Chef
anExpert.serve();
anExpert = new Expert(new Painting()); //this expert is Painter
anExpert.serve();
}
}
public class MyHouse
{
private boolean chairBroken = true;
public boolean isChairBroken()
{
return this.chairBroken;
}
private class RepairingFurniture implements Talent
{
public void showTalent()
{
if (chairBroken == true)
{
chairBroken = false;
}
}
} //end of private class
public static void main(String[] args)
{
MyHouse myHouse = new MyHouse();
if (myHouse.isChairBroken())
{
System.out.println("The chair needs to be fixed");
}
else
{
System.out.println("The chair has been fixed");
}
Expert anExpert = new Expert(myHouse.new RepairingFurniture()); //an
Expert with talent of RepairingFurniture (a carpenter) is in my house now.
anExpert.serve(); //this expert will fix the chair for us!!!
if (myHouse.isChairBroken())
{
System.out.println("The chair needs to be fixed");
}
else
{
System.out.println("The chair has been fixed");
}
}
}
</code>