编写Java程序,用户在网上购买商品(good),当用户买了一本书(book)、一顶帽子(hat)或者买了一双鞋子(shoe),卖家就会通过物流将商品邮寄给用户,使用简单工厂模式模拟这一过程。

查看本章节

查看作业目录


需求说明:

编写Java程序,用户在网上购买商品(good),当用户买了一本书(book)、一顶帽子(hat)或者买了一双鞋子(shoe),卖家就会通过物流将商品邮寄给用户,使用简单工厂模式模拟这一过程。

实现思路:

(1)创建商品Goods 类,声明String 类型的name,double 类型的price。定义一个包含 name 属性和 price 属性的有参构造方法。创建抽象方法getGoodsInfo(),目的是输出商品信息。

(2)创建帽子类 Hat、书籍类 Book 和鞋子类 Shoe,并让 3 个类继承抽象商品类 Goods,重写抽象方法。

(3)创建卖家类 SellerFactory,该类是简单工厂模式中的工厂角色类。创建静态方法 Goods sellGoods(String type, String name, double price),该方法用于返回商品对象,也是工厂角色的产品生产方法。在该方法内判断 type 的值,返回不同的商品对象。

(4) 创建工厂测试类 TestFactory, 在该类的程序入口main() 方 法 内,调用工厂类SellerFactory 的 工厂方 法 Goods sellGoods(String type, String name, double price), 获取具体产品实例,调用该实例的getGoodsInfo() 方法,输出该商品的具体信息。

实现代码:

商品Goods 类

public abstract class Goods {

	private String name;// 商品名称
	private double price; // 商品单价

	public Goods(String name, double price) {
		super();
		this.name = name;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	// 打印商品信息
	public void printGoodsInfo() {
		System.out.println("用户购买的商品是:" + this.getName() + ",价格是:" + this.getPrice() + "元");
	}
}

帽子类 Hat

public class Hat extends Goods {
	public Hat(String name, double price) {
		super(name, price);
	}
}

书籍类 Book

public class Book extends Goods {
	public Book(String name, double price) {
		super(name, price);
	}
}

鞋子类 Shoe

public class Shoe extends Goods {
	public Shoe(String name, double price) {
		super(name, price);
	}
}

卖家类 SellerFactory

public class SellerFactory {
	public static Goods sellGoods(String type, String name, double price) {
		Goods goods = null;
		// 判断用户购买的商品类型
		if ("帽子".equals(type)) {
			goods = new Hat(name, price);
		} else if ("书籍".equals(type)) {
			goods = new Book(name, price);
		} else if ("鞋子".equals(type)) {
			goods = new Shoe(name, price);
		}
		return goods;
	}
}

工厂测试类 TestFactory

public class TestFactory2 {
	public static void main(String[] args) {
		Goods goods = SellerFactory.sellGoods("书籍", "《大话设计模式》", 66);
		goods.printGoodsInfo();
	}
}

 

posted @ 2020-10-14 20:01  明金同学  阅读(57)  评论(0编辑  收藏  举报