首页 > 代码库 > strategy(策略模式)
strategy(策略模式)
DiscountStrategy.java
package edu.strategy; abstract public class DiscountStrategy { abstract public double calculateDiscount(); }
FlatRateStrategy.java
package edu.strategy; public class FlatRateStrategy extends DiscountStrategy { private double amount; private double price = 0; private int copies = 0; public FlatRateStrategy(double price, int copies) { this.setPrice(price); this.copies = copies; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public double calculateDiscount() { return copies * amount; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
NoDiscountStrategy.java
package edu.strategy; public class NoDiscountStrategy extends DiscountStrategy { private double price = 0.0; private int copies = 0; public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCopies() { return copies; } public void setCopies(int copies) { this.copies = copies; } public NoDiscountStrategy(double price, int copies) { this.price = price; this.copies = copies; } public double calculateDiscount() { return 0.0; } }
PercentageStrategy.java
package edu.strategy; public class PercentageStrategy extends DiscountStrategy { private double percent = 0.0; private double price = 0.0; private int copies = 0; public PercentageStrategy(double price, int copies) { this.price = price; this.copies = copies; } public double getPercent() { return percent; } public void setPercent(double percent) { this.percent = percent; } public double calculateDiscount() { return copies * price * percent; } }
调用如下
Context.java
package edu.strategy.test; public class Context { private Strategy strategy; /* * 策略方法 */ public void contextInterface(){ strategy.strategyInterface(); } }
ContextStrategy.java
package edu.strategy.test; public class ContextStrategy extends Strategy { /* * 策略方法 * * @see edu.strategy.Strategy#strategyInterface() */ @Override public void strategyInterface() { } }
Strategy.java
package edu.strategy.test; abstract public class Strategy { /* * 策略方法 */ public abstract void strategyInterface(); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。