Java 策略模式几种实现方式
策略模式是一种常见的设计模式,它可以让一个类的行为或其算法在运行时更改。在策略模式中,创建表示各种策略的对象,并在运行时切换对象。本文将详细介绍在Java中实现策略模式的几种方式。
策略模式概述
策略模式包含三个部分:上下文(Context)、策略(Strategy)和具体策略(Concrete Strategy)。上下文持有一个策略对象,并在需要执行特定策略时调用策略对象的方法。具体策略实现了策略接口定义的方法,并提供特定的算法实现。
例如,假设有一个商场销售系统,不同的商品可以根据不同的优惠策略来计算折扣价格。可以使用策略模式来实现这一功能。
第一种方式:使用接口定义策略
首先,我们定义一个策略接口DiscountStrategy
,该接口包含一个getDiscount
方法用于计算折扣价格。
public interface DiscountStrategy {
double getDiscount(double price);
}
然后,我们实现两个具体的策略类NormalDiscount
和VIPDiscount
,分别对应普通用户和VIP用户的折扣策略。
public class NormalDiscount implements DiscountStrategy {
@Override
public double getDiscount(double price) {
return price * 0.8; // 普通用户打八折
}
}
public class VIPDiscount implements DiscountStrategy {
@Override
public double getDiscount(double price) {
return price * 0.6; // VIP用户打六折
}
}
最后,我们定义上下文类PriceCalculator
,该类持有一个DiscountStrategy
对象,并提供一个方法用于计算最终价格。
public class PriceCalculator {
private DiscountStrategy discountStrategy;
public PriceCalculator(DiscountStrategy discountStrategy) {
this.discountStrategy = discountStrategy;
}
public double calculate(double price) {
return discountStrategy.getDiscount(price);
}
}
现在我们可以使用策略模式计算不同用户的折扣价格。
public class Main {
public static void main(String[] args) {
PriceCalculator normalCalculator = new PriceCalculator(new NormalDiscount());
double normalPrice = normalCalculator.calculate(100.0);
System.out.println("Normal Price: " + normalPrice);
PriceCalculator vipCalculator = new PriceCalculator(new VIPDiscount());
double vipPrice = vipCalculator.calculate(100.0);
System.out.println("VIP Price: " + vipPrice);
}
}
运行结果如下:
Normal Price: 80.0
VIP Price: 60.0
通过上述代码示例,我们实现了使用接口定义策略的方式来实现策略模式。
第二种方式:使用枚举定义策略
除了使用接口定义策略,我们还可以使用枚举定义策略。这种方式可以减少类的数量,使代码更加简洁。
首先,我们定义一个枚举类型DiscountType
,包含不同的折扣类型。
public enum DiscountType {
NORMAL {
@Override
public double getDiscount(double price) {
return price * 0.8;
}
},
VIP {
@Override
public double getDiscount(double price) {
return price * 0.6;
}
};
public abstract double getDiscount(double price);
}
接着,我们定义上下文类PriceCalculator
,该类持有一个DiscountType
对象,并提供一个方法用于计算最终价格。
public class PriceCalculator {
private DiscountType discountType;
public PriceCalculator(DiscountType discountType) {
this.discountType = discountType;
}
public double calculate(double price) {
return discountType.getDiscount(price);
}
}
我们可以使用枚举定义策略来计算不同用户的折扣价格。
public class Main {
public static void main(String[] args) {
PriceCalculator normalCalculator = new PriceCalculator(DiscountType.NORMAL);
double normalPrice = normalCalculator.calculate(100.0);
System.out.println("Normal Price: " + normalPrice);
PriceCalculator vipCalculator = new PriceCalculator(DiscountType.VIP);
double vipPrice = vipCalculator.calculate(100.0);
System.out.println("VIP Price: " + vipPrice);
}
}
运行结果如下:
Normal Price: 80.0
VIP Price: 60.0
通过上述代码示例,我们实现了使用枚举定义策略的方式来实现策略模式。
总结
本文介绍了在Java中实现策略模式的两种方式:使用接口定义策略和使用枚举定义策略。策略模式可以让程序更加灵活,易于扩展和维护。根据具体情况选择不同的实现方式,能够更好地应对需求变化。