Java技术:买水果。Java技术买水果计划代码
代码演示
class TestClass {
static String FRUIT_MANGO = "MANGO";
static String FRUIT_APPLE = "APPLE";
static String FRUIT_BERRY = "BERRY";
public static void main(String[] args) {
//要买的水果,硬编码
Fruit [] fruits = {
GeneFruit.getFruit(FRUIT_MANGO, 50d, 3),
GeneFruit.getFruit(FRUIT_APPLE, 30d, 5),
GeneFruit.getFruit(FRUIT_BERRY, 10d, 10)};
//参与满减
boolean flag = true;
try{
//买单,导包原因此处未使用BigDecimal,会导致精度丢失
double sum = payBill(fruits);
System.out.println("原价须付"+sum+"元");
//当有折扣和减免时,硬编码
double discount = 0.8d;
double reduction = 5d;
System.out.println("参加折扣和直接见面后须付"
+ String.format("%.2f",
CountPrice.getPrice(sum,discount,
reduction))
+"元 (原价:" + sum +
"元,折扣:" + discount
+"元,直接减免:" + reduction
+"元。)");
//有折扣、减免、满减的情况
if(flag){
System.out.println("参与满100减10活动后须付"+
String.format("%.2f",
CountPrice.getPriceA(sum,discount,
reduction,flag))
+ "元。");
}
}catch(Exception e){
System.out.println("计算价格抛出异常,此处进行异常处理!");
}
}
/**
* 买单
*/
static double payBill(Fruit [] fruits) throws Exception{
double sum = 0d;
for(Fruit f : fruits){
sum += f.sumPrice();
}
return sum;
}
}
/**
* 计价类
* 业务逐渐复杂化,添加了折扣或者减免时,为提高代码可读性,将计价逻辑单独提 出来
* */
class CountPrice{
static double sumPrice = 0d;
//参与折扣和减免
static double getPrice(
double oriPrice,
double discount,
double reduction){
sumPrice = oriPrice*discount-reduction;
return sumPrice;
}
/**
* 参与折扣、减免、满减
* 假设是在打完折和减去减免的基础上再满减
* */
static double getPriceA(
double oriPrice,
double discount,
double reduction,
boolean flag){
//满减次数
int ct = 0;
//参与满减前的总价
sumPrice = oriPrice*discount-reduction;
// 此处硬编码,满100减10元
if(flag){
ct = (int)sumPrice / 100;
if(ct >= 1)
sumPrice -= ct*10;
}
return sumPrice;
}
}
/**
*水果类
*/
abstract class Fruit{
public double price;
public int weight;
//计算单种水果总价格
public double sumPrice()throws Exception{
return price*weight;
}
}
/**
* 芒果类
* */
class Mango extends Fruit{
Mango(double price, int weight){
this.price = price;
this.weight = weight;
}
}
/**
* 苹果类
* */
class Apple extends Fruit{
Apple(double price, int weight){
this.price = price;
this.weight = weight;
}
}
/**
* 草莓类
* */
class Berry extends Fruit{
Berry(double price, int weight){
this.price = price;
this.weight = weight;
}
}
/**
* 工厂模式:工厂类
* */
class GeneFruit{
static Fruit getFruit(String name, double price, int weight){
Fruit fruit = null;
switch(name){
case "MANGO":
fruit = new Mango(price, weight);
break;
case "APPLE":
fruit = new Apple(price, weight);
break;
case "BERRY":
fruit = new Berry(price, weight);
break;
}
return fruit;
}
}
温馨提示:
1.本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:duhaomu@163.com,我们将第一时间处理!
2.资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。
3.所有资源仅限于参考和学习,版权归原作者所有,更多请阅读网站声明。
1.本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:duhaomu@163.com,我们将第一时间处理!
2.资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。
3.所有资源仅限于参考和学习,版权归原作者所有,更多请阅读网站声明。