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);
}
}
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下