定义类:Hat(帽子类)
属性:color(int类型);price(int类型);type(String类型)
提供空参,满参构造,set、get方法
2) 定义接口 :Factory(生产帽子类)
抽象方法:void describe(Hat hat);
抽象方法:ArrayList<Hat> piliang(int num);
3) 定义类:FactoryImp(生产帽子实现类)
实现接口Factory;
重写抽象方法void describe(Hat hat):方法内判断hat的color值,若为奇数是红色,
若为偶数为黄色,并打印该帽子的所有属性(颜色需打印判断后的值:红色或黄色)。
重写抽象方法ArrayList<Hat> piliang(int num):使用for循环生成num个Hat对象,
存入集合中,然后返回集合。对象的color属性随机赋值,price属性随机生成:范围为20-100(包含20和100),
type属性赋值为太阳帽。
4) 测试类:
a. 创建FactoryImp对象。
b. 调用方法ArrayList<Hat> piliang(int num),批量生产5个帽子,并接收。
c. 遍历接收的集合,调用方法void describe(Hat hat)打印集合中对象的属性。

解决方案 »

  1.   


    /**
     * 帽子类
     * @author 枫雅
     * 2019年3月19日
     */
    public class Hat {
    private int color;
    private int price;
    private String type;

    public Hat() {
    // TODO Auto-generated constructor stub
    }

    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;
    }

    @Override
    public String toString() {
    return "color:" + Integer.toString(color) + ", price:" + Integer.toString(price) + ", type:" + type;
    }
    }import java.util.ArrayList;/**
     * 生产帽子类
     * @author 枫雅
     * 2019年3月19日
     */
    public interface Factory {
    void describe(Hat hat);
    ArrayList<Hat> piliang(int num);
    }import java.util.ArrayList;
    import java.util.List;/**
     * 生产帽子实现类
     * @author 枫雅
     * 2019年3月19日
     */
    public class FactoryImp implements Factory{ @Override
    public void describe(Hat hat) {
    System.out.print(hat + ",");
    if (hat.getColor() % 2 == 0) {
    //黄色
    System.out.println("该帽子颜色为:黄色");
    }else {
    //红色
    System.out.println("该帽子颜色为:红色");
    }
    } @Override
    public ArrayList<Hat> piliang(int num) {
    List<Hat>list = new ArrayList<Hat>(num);
    for (int i = 0; i < num; i++) {
    Hat hat = new Hat((int)(Math.random()*10), (int)(Math.random()*81 + 20), "太阳帽");
    list.add(hat);
    }
    return (ArrayList<Hat>)list;
    }}import java.util.List;/**
     * 测试类
     * @author 枫雅
     * 2019年3月19日
     */
    public class TestHat {
    private static List<Hat>list = null;
    public static void main(String[] args) {
    FactoryImp imp = new FactoryImp();
    list = imp.piliang(5);
    for (int i = 0; i < 5; i++) {
    imp.describe(list.get(i));
    }
    }}