A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 合斐 初级黑马   /  2018-12-15 13:04  /  450 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


首先定义一个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));
    }
}





1544849548(1).png

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马