工厂模式和策略模式都是广泛使用的模式,它们各自解决了不同层面的问题。接下来将分别介绍这两种模式的基本概念、特点以及应用场景。
工厂模式是一种创建型设计模式,它提供了创建对象的最佳方式。在工厂模式中,在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。工厂模式的核心思想是将对象的创建与使用分离,通过一个工厂类来负责创建产品族中的各种实例。
在这个例子中,工厂模式用于创建不同类型的咖啡。
// 咖啡接口
interface Coffee {
void brew();
}
// 具体的咖啡类
class Espresso implements Coffee {
@Override
public void brew() {
System.out.println("制作浓缩咖啡");
}
}
class Latte implements Coffee {
@Override
public void brew() {
System.out.println("制作拿铁咖啡");
}
}
// 咖啡工厂
class CoffeeFactory {
public Coffee createCoffee(String type) {
if ("espresso".equalsIgnoreCase(type)) {
return new Espresso();
} else if ("latte".equalsIgnoreCase(type)) {
return new Latte();
}
throw new IllegalArgumentException("未知的咖啡类型");
}
}
// 使用
public class CoffeeShop {
public static void main(String[] args) {
CoffeeFactory factory = new CoffeeFactory();
Coffee espresso = factory.createCoffee("espresso");
espresso.brew(); // 输出:制作浓缩咖啡
Coffee latte = factory.createCoffee("latte");
latte.brew(); // 输出:制作拿铁咖啡
}
}
在这个例子中,工厂模式用于创建不同类型的咖啡对象。客户端只需要知道想要的咖啡类型,而不需要了解具体的咖啡类。
策略模式是一种行为型设计模式,它定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。策略模式让算法独立于使用它的客户端。
使用策略模式来处理咖啡的定价策略。
// 定价策略接口
interface PricingStrategy {
double calculatePrice(double basePrice);
}
// 具体的定价策略
class RegularPricing implements PricingStrategy {
@Override
public double calculatePrice(double basePrice) {
return basePrice; // regular price, no discount
}
}
class DiscountPricing implements PricingStrategy {
@Override
public double calculatePrice(double basePrice) {
return basePrice * 0.9; // 10% discount
}
}
class HappyHourPricing implements PricingStrategy {
@Override
public double calculatePrice(double basePrice) {
return basePrice * 0.5; // 50% discount during happy hour
}
}
// 咖啡订单类
class CoffeeOrder {
private PricingStrategy pricingStrategy;
private double basePrice;
public CoffeeOrder(double basePrice) {
this.basePrice = basePrice;
this.pricingStrategy = new RegularPricing(); // 默认使用常规定价
}
public void setPricingStrategy(PricingStrategy pricingStrategy) {
this.pricingStrategy = pricingStrategy;
}
public double getFinalPrice() {
return pricingStrategy.calculatePrice(basePrice);
}
}
// 使用
public class CoffeeShopPricing {
public static void main(String[] args) {
CoffeeOrder order = new CoffeeOrder(5.0); // 咖啡基础价格为 $5
System.out.println("Regular price: $" + order.getFinalPrice());
order.setPricingStrategy(new DiscountPricing());
System.out.println("Discounted price: $" + order.getFinalPrice());
order.setPricingStrategy(new HappyHourPricing());
System.out.println("Happy hour price: $" + order.getFinalPrice());
}
}
在这个例子中,策略模式用于在运行时改变价格计算的方法。咖啡订单类可以动态地改变其定价策略,而无需修改订单类的代码。
尽管工厂模式和策略模式在某些方面相似,但它们之间还是存在明显的区别:
工厂模式和策略模式都是设计模式的重要组成部分。工厂模式关注于对象的创建过程,而策略模式则关注于算法的选择与替换。理解它们之间的差异有助于在设计时做出合适的选择。