沿用女娃造人的故事:
我们把造人的炉子抽象一下,分成个来造,白色的炉子造白人,黑色的炉子造黑人,黄色的炉子造黄种人。
那么:
人的接口:
public interface Human {
//会说话
public void talk();
//会笑
public void laugh();
//会哭
public void cry();
}
黄种人:
public class YellowHuman implements Human{
@Override
public void talk() {
System.out.println("黄种人会说话");
}
@Override
public void laugh() {
System.out.println("黄种人会笑!");
}
@Override
public void cry() {
System.out.println("黄宏人会哭!");
}
}
白种人:
public class WhiteHuman implements Human{
@Override
public void talk() {
System.out.println("白种人会说话!");
}
@Override
public void laugh() {
System.out.println("白种人会笑!");
}
@Override
public void cry() {
System.out.println("白种人会哭!");
}
}
黑种人:
public class BlockHuman implements Human{
@Override
public void talk() {
System.out.println("黑种人会说话!");
}
@Override
public void laugh() {
System.out.println("黑种人会笑!");
}
@Override
public void cry() {
System.out.println("黑种人会哭!");
}
}
炉子:
public interface HumanFactory {
public Human createHuman();
}
黄色的炉子:
public class YellowFactory implements HumanFactory {
@Override
public Human createHuman() {
return new YellowHuman();
}
}
黑色的炉子:
public class BlockFactory implements HumanFactory {
@Override
public Human createHuman() {
return new BlockHuman();
}
}
白色的炉子:
public class WhiteFactory implements HumanFactory {
@Override
public Human createHuman() {
return new WhiteHuman();
}
}
女娲:
public class NvWa {
public static void main(String[] args) {
//先来一堆白人
System.out.println("白人来咯:");
WhiteFactory wf = new WhiteFactory();
Human whiteHuman = wf.createHuman();
whiteHuman.cry();
whiteHuman.laugh();
whiteHuman.talk();
//再来一堆黑人
System.out.println("黑人来咯:");
Human blockHuman = new BlockFactory().createHuman();
blockHuman.talk();
blockHuman.laugh();
blockHuman.cry();
//最后来一批黄种人
System.out.println("黄种人来咯:");
Human yellowHuman = new YellowFactory().createHuman();
yellowHuman.cry();
yellowHuman.laugh();
yellowHuman.talk();
}
}
看造人结果: