首先定义一个Hat类
private int color;//颜色
private int price;//价格
private String type;//样式
public Hat() {
}
public Hat(int color, int price, String type) {
this.color = color;
this.price = price;
this.type = type;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}定义一个Factory接口public interface Factory {
void describe(Hat hat);
ArrayList<Hat> piliang(int num);
定义实现类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));
}
}
|
|