定义实现类FactoryImp;(重点部分) public class FactoryImp implements Factory {
@Override public void describe(Hat hat) {
if (hat.getColor()%2==0){
System.out.println("颜色为黄色,价格为:"+hat.getPrice()+"元的"+hat.getType());
}else {
System.out.println("颜色为红色,价格为:"+hat.getPrice()+"元的"+hat.getType());
}
}
@Override public ArrayList<Hat> piliang(int num) {
Random random = new Random();
ArrayList<Hat> hats = new ArrayList<>(); for (int i = 0; i < num; i++) { int i1 = random.nextInt(81)+20; int i2 = random.nextInt();
Hat hat = new Hat(i2,i1,"太阳帽");
hats.add(hat);
} return hats;
}
}
最后测试类FactoryImp;public static void main(String[] args) {
FactoryImp factoryImp = new FactoryImp();
ArrayList<Hat> piliang = factoryImp.piliang(5); for (int i = 0; i < piliang.size(); i++) {
factoryImp.describe(piliang.get(i));
}
}