马士兵策略模式视频:链接: 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方法。