b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

解释器模式举例_lua解释器交互模式_动态编译与解释器模式(43)

电脑杂谈  发布时间:2017-02-22 17:29:35  来源:网络整理

比如说,我们往回一些年,那时候的相机不是每个人都会用的,按下快门前还需要调焦等操作,然而现在呢,我们拍照只需要按下快门就行了,中间的一系列操作都被自动执行了。外观模式也就是提供这样一种机制。

我们在使用一个有代码的例子:用户要购买一件商品,系统首先会判断库存,然后要计算费用(商品价,邮费和优惠等),最后才会生成一个订单。这其中就包含几个子系统,库存管理子系统和计费子系统,而计费子系统又分更小的子系统(此处两处使用到外观模式)。

获取商品原价的子系统:

//获取商品价public class ProductPrice {    int getPrice(String product){        return Math.abs(product.hashCode());//模拟获取商品价    }}

获取邮费的子系统:

//计算邮费public class Postage {    int getPostage(String addr){        return Math.abs(addr.hashCode())%206;//模拟邮费计算    }}

计算优惠的子系统:

//计算优惠public class Discount {    int getDiscount(String discountCode){        return Math.abs(discountCode.hashCode())%3;    }}

计算最终价的子系统,同时他也是一个外观,因为它含有以上三个子系统的引用:

//计费子系统public class FinalPrice {    ProductPrice productPrice;    Postage postage;    Discount discount;    public FinalPrice(){        productPrice = new ProductPrice();        postage = new Postage();        discount = new Discount();    }    int getFinalPrice(String product,String addr,String discountCode){        return productPrice.getPrice(product)postage.getPostage(addr)-discount.getDiscount(discountCode);    }}

库存子系统:

//库存子系统public class Stock {    boolean hasStock(String product){        return new Random().nextInt(Math.abs(product.hashCode()))>0;//模拟是否还有库存    }}

最后是面向用户的购买接口,在这里也是一个外观,同时,这里使用了枚举实现的单例模式:

//外观public enum ProductSalesman {    instance;    Stock stock = new Stock();    FinalPrice finalPrice = new FinalPrice();    Object buySomething(String product,String addr,String discountCode){        if(!stock.hasStock(product))            return "库存不足";        int price = finalPrice.getFinalPrice(product, addr, discountCode);        return "订单信息:"  product  "-"  addr  "-"   discountCode  "-"   price;    }}


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-33893-43.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    • 哀平帝苻丕
      哀平帝苻丕

      必须给他弄沉

    • 刘安华
      刘安华

      中国还没有宣布这三个新岛的领海基点吧

    热点图片
    拼命载入中...