设计模式——策略模式

马士兵策略模式视频:链接: https://pan.baidu.com/s/1DNbRbT_OL8M3H_s0XFyq_Q 密码: l0r9(通过讲源码的原型来讲模式)

参照视频讲的,写了一个略粗糙的商品打折的小demo

首先定义了两个接口,分别是Discountable(能够打折的对象)和Discountor(打折器--决定何种打折方式--策略)

public interface Discountable {
    double discount(Product d);
}

 

public interface Discountor {
    double discountTo(Product d1,Product d2);
}

Product商品能够打折,需要实现Discountable接口,并重写具体的discount方法

public class Product implements Discountable {
    private int price;
    private Discountor discountor;

    public Product(int price, Discountor discountor){
        this.price = price;
        this.discountor = discountor;
    }
    public int getPrice() {
        return price;
    }

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

    public Discountor getDiscountor() {
        return discountor;
    }

    public void setDiscountor(Discountor discountor) {
        this.discountor = discountor;
    }

    @Override
    public double discount(Product d) {
        return discountor.discountTo(this,d);
    }
}

其中,new Product时,需要制定商品的打折策略

打折策略由具体的打折器确认,需要实现Discountor接口

五折

public class Discount50 implements Discountor {
    private static Discount50 discount50;
    private Discount50(){};
    public static Discount50 getInstance() {
        if (discount50 == null) {
            discount50 = new Discount50();
        }
        return discount50;
    }

    @Override
    public double discountTo(Product p1, Product p2) {
        return (p1.getPrice()+p2.getPrice())/2;
    }
}

三五折

public class Discount35 implements Discountor{
    private static Discount35 discount35;
    private Discount35(){};
    public static Discount35 getInstance() {
        if (discount35 == null) {
            discount35 = new Discount35();
        }
        return discount35;
    }

    @Override
    public double discountTo(Product p1, Product p2) {
        return (p1.getPrice()+p2.getPrice())*0.35;
    }
}

收银员结算商品时

这里写的比较简单,就两种商品,实际情况下 count的parmater应该用production  ...表示

public class Client {
    public static void main(String[] args) {
        Discountor boagof = Discount35.getInstance();
        Product product1 = new Product(100,boagof);
        Product product2 = new Product(200,boagof);
        if (product1.getDiscountor().equals(product2.getDiscountor())) {
            //同一个打折器可以实现统一折扣
            count(product1, product2);
        }
    }

    public static double count(Product p1, Product p2) {
        double discountPrice = p1.discount(p2);
        System.out.println(discountPrice);
        return discountPrice;
    }

}

策略模式体现在:若商品的打折方式有变,直接新建打折器就好,不需要修改其中的discount方法。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值