还是那个女娲造人的故事,先把人类的模型创建出来
创造个接口,叫IHuman;
public abstract void getColor();
public abstract void talk();
}
然后创建三个类,分别是BlackHuman,WhiteHuman,YellowHuman ,这三个类都继承了IHuman这个接口;
BlackHuman:
public class BlackHuman implements IHuman {
@Override
public void getColor() {
System.out.println("黑种人");
}
@Override
public void talk() {
System.out.println("黑种人说话了");
}
}
WhiteHuman:
public class WhiteHuman implements IHuman {
@Override
public void getColor() {
System.out.println("白种人");
}
@Override
public void talk() {
System.out.println("白种人说话了");
}}
YellowHuman:
public class YellowHuman implements IHuman {
@Override
public void getColor() {
System.out.println("黄种人");
}
@Override
public void talk() {
System.out.println("黄种人说话了");
}
}
然后再创建一个接口,取名IHumanFactory,这就像是一个炼丹炉的模型
public interface IHumanFactory {
public abstract IHuman createHuman(String human);
}
然后再创建一个类,取名HumanFactory,继承了IHumanFactory这个接口:
public class HumanFactory implements IHumanFactory {
public static final String BlackHuman = "blackHuman";
public static final String WhiteHuman = "whiteHuman";
public static final String YellowHuman = "yellowHuman";
public static HumanFactory humanFactory = null;
private HumanFactory(){
}
/*
/*这里设置了一个单列模式
/*
public static HumanFactory getIntance(){
if(humanFactory == null){
humanFactory = new HumanFactory();
}
return humanFactory;
}
/*
/*重写了IHumanFactory接口,判断两边是否相等,并将数值返回;
/*
@Override
public IHuman createHuman(String human) {
if(human.equals(HumanFactory.BlackHuman)){
return new BlackHuman();
}else if(human.equals(HumanFactory.WhiteHuman)){
return new WhiteHuman();
}else if(human.equals(HumanFactory.YellowHuman)){
return new YellowHuman();
}
return null;
}
}
创建一个类,这个就是程序入口,如果想创造哪个人类,可以直接在这里添加:
public class Client {
public static void main(String[] args) {
BlackHuman bh = (BlackHuman)HumanFactory.getIntance().createHuman(HumanFactory.BlackHuman);
bh.getColor();
WhiteHuman wh = (WhiteHuman)HumanFactory.getIntance().createHuman(HumanFactory.WhiteHuman);
wh.getColor();
YellowHuman yh = (YellowHuman)HumanFactory.getIntance().createHuman(HumanFactory.YellowHuman);
yh.getColor();
}
}