構造パターン
互換性のないインターフェースを持つクラス同士を接続する。既存コードを変更せずに新しいインターフェースに適合させる。
public interface PaymentGateway {
PaymentResult processPayment(String orderId, int amount, String currency);
PaymentStatus checkStatus(String transactionId);
}
public class StripeApi {
public StripeCharge createCharge(StripeChargeRequest request) {
return new StripeCharge();
}
public StripeCharge retrieveCharge(String chargeId) {
return new StripeCharge();
}
}
public class StripePaymentAdapter implements PaymentGateway {
private final StripeApi stripeApi;
public StripePaymentAdapter(StripeApi stripeApi) {
this.stripeApi = stripeApi;
}
@Override
public PaymentResult processPayment(String orderId, int amount, String currency) {
// 自社形式 → Stripe形式に変換
StripeChargeRequest request = new StripeChargeRequest();
request.setAmount(amount * 100L); // 円→セント変換
request.setCurrency(currency.toLowerCase());
StripeCharge charge = stripeApi.createCharge(request);
// Stripe形式 → 自社形式に変換
return new PaymentResult(charge.getId(), charge.getStatus().equals("succeeded"));
}
@Override
public PaymentStatus checkStatus(String transactionId) {
StripeCharge charge = stripeApi.retrieveCharge(transactionId);
return convertStatus(charge.getStatus());
}
}
StripeApi stripeApi = new StripeApi();
PaymentGateway payment = new StripePaymentAdapter(stripeApi);
// 自社インターフェースで操作
PaymentResult result = payment.processPayment("ORDER-001", 1000, "JPY");
// 別サービスへの切り替えも容易
PaymentGateway paypal = new PayPalPaymentAdapter(new PayPalApi());
以下のAdapterパターンを作成してください。 【自社インターフェース】 FileStorage ・upload(String path, byte[] data): String ・download(String path): byte[] ・delete(String path): boolean 【適合させたい外部API】 AWS S3 SDK 【必要な変換】 ・パス形式: 自社形式 → S3形式(bucket + key) ・エラーハンドリング: S3例外 → 自社例外