好的,以下是Java的一个工厂模式策略模式和装饰器模式组合使用的示例代码:
首先,我们需要定义一个接口作为策略模式的策略:
```
public interface PaymentStrategy {
public void pay(double amount);
}
```
接下来,我们需要实现两种不同的支付方式——信用卡支付和PayPal支付:
```
public class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
private String cvv;
private String expirationDate;
public CreditCardPayment(String cardNumber, String cvv, String expirationDate) {
this.cardNumber = cardNumber;
this.cvv = cvv;
this.expirationDate = expirationDate;
}
@Override
public void pay(double amount) {
// 信用卡支付逻辑
System.out.println(amount + " paid with credit/debit card");
}
}
public class PayPalPayment implements PaymentStrategy {
private String email;
private String password;
public PayPalPayment(String email, String password) {
this.email = email;
this.password = password;
}
@Override
public void pay(double amount) {
// PayPal支付逻辑
System.out.println(amount + " paid using PayPal");
}
}
```
然后,我们需要定义一个工厂类,根据不同条件生成对应的对象:
```
public class PaymentStrategyFactory {
public static PaymentStrategy getPaymentStrategy(String paymentType, Object... args) {
if(paymentType.equalsIgnoreCase("creditcard")) {
return new CreditCardPayment((String)args[0], (String)args[1], (String)args[2]);
} else if(paymentType.equalsIgnoreCase("paypal")) {
return new PayPalPayment((String)args[0], (String)args[1]);
} else {
return null;
}
}
}
```
最后,我们可以定义一个装饰器类来增加额外功能:
```
public abstract class PaymentDecorator implements PaymentStrategy{
protected PaymentStrategy paymentStrategy;
public PaymentDecorator(PaymentStrategy paymentStrategy){
this.paymentStrategy = paymentStrategy;
}
public void pay(double amount){
paymentStrategy.pay(amount);
}
}
```
然后在装饰器中增加额外功能:
```
public class DiscountedPayment extends PaymentDecorator {
public DiscountedPayment(PaymentStrategy paymentStrategy){
super(paymentStrategy);
}
public void pay(double amount) {
// 在原有支付方法上执行额外操作(如加减折扣等)
double discountAmount = amount * 0.9; // 打九折优惠
System.out.println("Discounted Price : "+discountAmount);
super.pay(discountAmount);
}
}
```
最终使用工厂模式、策略模式和装饰器模式组合起来:
```
public class TestPattern {
public static void main(String args[]) {
// 使用工厂方法创建策略对象,并通过装饰器来增加额外功能(这里是打九折优惠)
PaymentDecorator discountedCreditCard = new DiscountedPayment(PaymentFactory.getPaymentMethod("creditcard", "622202******", "123", "12/24"));
// 调用pay方法来执行具体的支付操作
discountedCreditCard.pay(1200);
}
}
设计模式混合使用
最新推荐文章于 2023-04-15 23:54:13 发布