Java设计模式之Strategy模式
基于有了OO的基础后,开始认真学习设计模式!设计模式是java设计中必不可少的!
Apple.java
packagestrategy;
/**
*
*@authorAndy
*
*/
publicclassAppleimplementsDiscountable{
//重量
privatedoubleweight;
//单价实际开发中设计金钱等精确计算都是BigDecimal;
privatedoubleprice;
//按购买量打折
//privateDiscountord=newAppleWeightDiscountor();
//按购买总价打折
privateDiscountord=newApplePriceDiscountor();
publicdoublegetWeight(){
returnweight;
}
publicvoidsetWeight(doubleweight){
this.weight=weight;
}
publicdoublegetPrice(){
returnprice;
}
publicvoidsetPrice(doubleprice){
this.price=price;
}
publicApple(doubleweight,doubleprice){
super();
this.weight=weight;
this.price=price;
}
@Override
publicvoiddiscountSell(){
d.discount(this);
}
}
Banana.java
packagestrategy;
/**
*
*@authorAndy
*
*/
publicclassBananaimplementsDiscountable{
//重量
privatedoubleweight;
////单价实际开发中涉及金钱等精确计算都是用BigDecimal
privatedoubleprice;
publicBanana(doubleweight,doubleprice){
super();
this.weight=weight;
this.price=price;
}
publicdoublegetWeight(){
returnweight;
}
publicvoidsetWeight(doubleweight){
this.weight=weight;
}
publicdoublegetPrice(){
returnprice;
}
publicvoidsetPrice(doubleprice){
this.price=price;
}
@Override
publicvoiddiscountSell(){
//打折算法
if(weight<5){
System.out.println("Banana未打折价钱:"+weight*price);
}elseif(weight>=5&&weight<10){
System.out.println("Banana打八八折价钱:"+weight*price*0.88);
}elseif(weight>=10){
System.out.println("Banana打五折价钱:"+weight*price*0.5);
}
}
}
Market.java
packagestrategy;
/**
*
*@authorAndy
*
*/
publicclassMarket{
/**
*对可打折的一类事物进行打折
*@paramapple
*/
publicstaticvoiddiscountSell(Discountabled){
d.discountSell();
}
}
Discountable.java
packagestrategy;
/**
*
*@authorAndy
*
*/
publicinterfaceDiscountable{
publicvoiddiscountSell();
}
Test.java
packagestrategy;
/**
*
*@authorAndy
*
*/
publicclassTest{
/**
*
*@paramargs
*/
publicstaticvoidmain(String[]args){
//只能对苹果打折还不能对通用的一类事物打折而且都是要卖什么就写什么打折算法
//其实每类事物打折算法又是不一致的
Discountabled=newApple(10.3,3.6);
Discountabled1=newBanana(5.4,1.1);
Market.discountSell(d);
Market.discountSell(d1);
}
}