Strategy pattern and factory pattern

 策略模式與工廠模式

策略模式

一組相似演算法,運行時選擇適當演算法

例如:支付系統,有支付介面,在以介面實作各種支付,要使用那種支付就建該支付物件

// 支付策略介面
interface PaymentStrategy {
void pay(int amount);
}
// 具體支付策略之一:信用卡支付
class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
// 具體支付策略之二:PayPal支付
class PayPalPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
// 支付上下文,用於設定和使用支付策略
class PaymentContext {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void performPayment(int amount) {
if (paymentStrategy != null) {
paymentStrategy.pay(amount);
} else {
System.out.println("Payment strategy not set.");
}
}
}
// 客戶端程式碼
public class Client {
public static void main(String[] args) {
PaymentContext paymentContext = new PaymentContext();
// 使用信用卡支付
paymentContext.setPaymentStrategy(new CreditCardPayment());
paymentContext.performPayment(100);
// 使用PayPal支付
paymentContext.setPaymentStrategy(new PayPalPayment());
paymentContext.performPayment(50);
}
}

工廠模式

解決建立物件問題,封裝建立物件過程

例如:形狀介面,以介面實作各種形狀,建立形狀工廠,使用時如shapeFactory.createShape("circle")來建立圓形物件

// 形狀介面
interface Shape {
void draw();
}
// 具體形狀之一:圓形
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
// 具體形狀之二:正方形
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing Square");
}
}
// 具體形狀之三:三角形
class Triangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Triangle");
}
}
// 形狀工廠,用於創建不同形狀的物件
class ShapeFactory {
public Shape createShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("Circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("Square")) {
return new Square();
} else if (shapeType.equalsIgnoreCase("Triangle")) {
return new Triangle();
}
return null;
}
}
// 客戶端程式碼
public class Client {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
// 創建圓形
Shape circle = shapeFactory.createShape("Circle");
circle.draw();
// 創建正方形
Shape square = shapeFactory.createShape("Square");
square.draw();
// 創建三角形
Shape triangle = shapeFactory.createShape("Triangle");
triangle.draw();
}
}


Comments

Popular posts from this blog

Format date as yyyy-mm-dd using vbscript

How to write data into a excel file using vbscript