使用泛型构建复杂模型Store商店

本文介绍了一个使用Java实现的商店模拟系统,该系统包括产品、货架、通道等元素,并通过泛型和生成器来填充商店的商品信息。系统展示了如何创建一个包含多个通道、每个通道有若干货架、每货架上摆放多种产品的商店布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package ding;   

import java.util.ArrayList;
import java.util.Random;

import ding.generics.Generators;

/**  
 * @author   E-mail:   
 * @version 2018年6月5日 下午9:31:42  
 */
class Product{
	private final int id;
	private String description;
	private double price;
	public Product(int IDnumber,String descr,double price){
		id = IDnumber;
		description = descr;
		this.price = price;
		System.out.println(toString());
	}
	public void priceChange(double change){
		price += change;
	}
	public static Generator<Product> generator = new Generator<Product>(){
		private Random rand = new Random(47);
		@Override
		public Product next() {
			return new Product(rand.nextInt(1000),"Test",Math.round(rand.nextDouble()*1000.0)+0.99);
		}
		
	};
	@Override
	public String toString() {
		return "Product [id=" + id + ", description=" + description
				+ ", price=" + price + "]";
	}
}
class Shelf extends ArrayList<Product>{
	public Shelf(int nProdects){
		Generators.fill(this, Product.generator, nProdects);
	}	
}
class Aisle extends ArrayList<Shelf>{
	public Aisle(int nShelves,int nProducts){
		for(int i=0;i<nShelves;i++)
			add(new Shelf(nProducts));
	}
}
class CheckoutStand{}
class Office{}

public class Store extends ArrayList<Aisle>{
	private ArrayList<CheckoutStand> checkouts = new ArrayList<CheckoutStand>();
	private Office office = new Office();
	public Store(int nAisles,int nShelves,int nProducts){
		for(int i=0;i<nAisles;i++)
			add(new Aisle(nShelves,nProducts));
	}
	public String toString(){
		StringBuilder result = new StringBuilder();
		for(Aisle a : this)
			for(Shelf s : a)
				for(Product p : s){
					result.append(p);
					result.append("\n");
				}
		return result.toString();
	}
	public static void main(String[] args) {
		System.out.println(new Store(14,5,10));
	}

}
 


package ding.generics;  

import java.util.Collection;
import ding.Generator;


/**  
 * @author dingaijie  E-mail:   
 * @version 2018年6月5日 上午8:47:34  
 */
public class Generators {
	public static <T> Collection<T> 
		fill(Collection<T> coll,Generator<T> gen,int n){
			for(int i=0;i<n;i++)
				coll.add(gen.next());
			return coll;
	}
}
 

package ding;   
/**  
 * @author   E-mail:   
 * @version 2018年6月4日 下午11:54:13  
 */
public interface Generator<T> {
	T next();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值