strategy模式 java_Java设计模式之Strategy模式

该博客介绍了如何在Java中应用设计模式来实现商品的打折策略。通过`Apple`和`Banana`类展示了如何根据商品重量或总价实现不同的打折算法。`Discountable`接口定义了打折方法,`Market`类用于调用不同商品的打折策略。博客强调了设计模式在Java设计中的重要性,使得代码更加灵活和可维护。
摘要由CSDN通过智能技术生成

基于有了OO的基础后,开始认真学习设计模式!设计模式是java设计中必不可少的!

Apple.java

package strategy;

/**

*

* @author Andy

*

*/

public class Apple implements Discountable {

//重量

private double weight;

//单价 实际开发中 设计金钱等精确计算都是BigDecimal;

private double price;

//按购买量打折

// private Discountor d = new AppleWeightDiscountor();

//按购买总价打折

private Discountor d = new ApplePriceDiscountor();

public double getWeight() {

return weight;

}

public void setWeight(double weight) {

this.weight = weight;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

public Apple (double weight,double price ){

super();

this.weight=weight;

this.price=price;

}

@Override

public void discountSell() {

d.discount(this);

}

}

Banana.java

package strategy;

/**

*

* @author Andy

*

*/

public class Banana implements Discountable {

//重量

private double weight;

单价 实际开发中 涉及金钱等精确计算都是用BigDecimal

private double price;

public Banana(double weight, double price) {

super();

this.weight = weight;

this.price = price;

}

public double getWeight() {

return weight;

}

public void setWeight(double weight) {

this.weight = weight;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

@Override

public void discountSell() {

//打折算法

if(weight < 5) {

System.out.println("Banana未打折价钱: " + weight * price);

}else if(weight >= 5 && weight < 10) {

System.out.println("Banana打八八折价钱: " + weight * price * 0.88 );

}else if(weight >= 10) {

System.out.println("Banana打五折价钱: " + weight * price * 0.5 );

}

}

}

Market.java

package strategy;

/**

*

* @author Andy

*

*/

public class Market {

/**

* 对可打折的一类事物进行打折

* @param apple

*/

public static void discountSell(Discountable d) {

d.discountSell();

}

}

Discountable.java

package strategy;

/**

*

* @author Andy

*

*/

public interface Discountable {

public void discountSell();

}

Test.java

package strategy;

/**

*

* @author Andy

*

*/

public class Test {

/**

*

* @param args

*/

public static void main(String[] args) {

// 只能对苹果打折 还不能对通用的一类事物打折 而且都是要卖什么就写什么打折算法

// 其实每类事物打折算法又是不一致的

Discountable d = new Apple(10.3, 3.6);

Discountable d1= new Banana(5.4,1.1);

Market.discountSell(d);

Market.discountSell(d1);

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值