Java设计模式之Strategy模式
时间:2021-07-02 09:00:03|栏目:JAVA代码|点击: 次
基于有了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);
}
}
栏 目:JAVA代码
下一篇:Java编程实现月食简单代码分享
本文标题:Java设计模式之Strategy模式
本文地址:http://www.codeinn.net/misctech/151498.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




