第173章
大b:“假设现在要设计一个贩卖各类书籍的电子商务网站的购物车(shoppingcat)系统。一个最简单的情况就是把所有货品的单价乘上数量,但是实际情况肯定比这要复杂。”
小a:“一般会有哪些情况哩?”
大b:“比如:1、可能对所有的儿童类图书实行每本一元的折扣;2、计算机类图书提供每本7%的促销折扣,而对电子类图书有3%的折扣;3、剩余的图书没有折扣。4、还会有新的打折策略。由于有这样复杂的折扣算法,使得价格计算问题需要系统地解决。”
方案一:业务逻辑放在各具体子类
/**//*
*各子类实现销售价格算法
*/
publicabstractclassbook……{
privatedoubleprice;
privatestringname;
publicstringgetname()……{
returnname;
}
publicvoidsetname(stringname)……{
this.name=name;
}
publicdoublegetprice()……{
returnprice;
}
publicvoidsetprice(doubleprice)……{
this.price=price;
}
publicabstractdoublegetsaleprice();
}
publicclasscsbookextendsbook……{
publiccsbook(stringname,doubleprice)
{
this.setname(name);
this.setprice(price);
}
publicdoublegetsaleprice()
……{
returnthis.getprice()*0.93;
}
}
publicclasschildrenbookextendsbook……{
publicchildrenbook(stringname,doubleprice)……{
this.setname(name);
this.setprice(price);
}
publicdoublegetsaleprice()……{
returnthis.getprice()-1;
}
}
publicclassclient……{
publicstaticvoidmain(stringargs[])
……{
bookcsbook1=newcsbook(“thinkinjava”,45);
bookchildrenbook1=newchildrenbook(“hello”,20);
system.out.println(csbook1.getname()+:+csbook1.getsaleprice());
system.out.println(childrenbook1.getname()+:+childrenbook1.getsaleprice());
}
}
问题:每个子类必须都各自实现打折算法,即使打折算法相同。所以codereuse不好
方案二:
//把打折策略代码提到父类来实现codereuse
publicabstractclassbook……{
privatedoubleprice;
privatestringname;
publicstringgetname()……{
returnname;
}
publicvoidsetname(stringname)……{
this.name=name;
}
publicdoublegetprice()……{
returnprice;
}
publicvoidsetprice(doubleprice)……{
this.price=price;
}
//销售价格
publicstaticdoubletosaleprice(bookbook)
……{
if(bookinstanceofchildrenbook)
……{
returnbook.getprice()-1;
}
elseif(bookinstanceofcsbook)
……{
returnbook.getprice()*0.93;
}
return0;
}
}
publicclassclient……{
publicstaticvoidmain(stringargs[])
……{
bookcsbook1=newcsbook(“thinkinjava”,45);
bookchildrenbook1=newchildrenbook(“hello”,20);
system.out.println(csbook1.getname()+:+book.tosaleprice(csbook1));
system.out.println(childrenbook1.getname()+:+book.tosaleprice(childrenbook1));
}
}
tosaleprice方法是比较容易change的地方,如果策略复杂用if判断比较乱,并且策略修改或增加时需改变原代码。
方案三:策略模式
codereuse时最好用合成(has-a)而不用(is-a),更加灵活。
publicabstractclassbook……{
privatedoubleprice;
privatestringname;
privatediscountstrategydiscountstrategy;//折扣策略
publicstringgetname()……{
returnname;
}
publicvoidsetname(stringname)……{
this.name=name;
}
publicdoublegetprice()……{
returnprice;
}
publicvoidsetprice(doubleprice)……{
this.price=price;
}
publicdiscountstrategygetdiscountstrategy()……{
returndiscountstrategy;
}