반응형
행동 패턴 - Strategy
해결하려는 문제
- 클라이언트에 독립적으로 문제 해결 전략을 바꾸고 싶을 때
- 다양한 문제해결 방법을 제공해야 할 때
public class Main {
private static CouponService couponService = new CouponService();
public static void main(String[] args) {
/*
Coupon discountCoupon = new DiscountCoupon(2000);
System.out.println(discountCoupon.calc(3000));
Coupon percentageCoupon = new PercentageCoupon(10);
System.out.println(percentageCoupon.calc(3000));
*/
// int productPrice = 1000;
Product ipadPro = new Product("아이패드 프로", 1500000);
Coupon percentageCoupon = couponService.getCoupon(10L);
int discountAmount = ipadPro.discount(percentageCoupon);
System.out.println("최종가격 : " + discountAmount);
// Coupon discountCoupon = couponService.getCoupon(500L);
// System.out.println(discountCoupon.calc(productPrice));
}
}
public interface Coupon {
int calc(int productAmount);
}
public class DiscountCoupon implements Coupon {
private int discount;
public DiscountCoupon(int discount) {
this.discount = discount;
}
@Override
public int calc(int productAmount) {
return Math.max(productAmount - discount, 0);
}
}
public class PercentageCoupon implements Coupon {
private int ratio;
public PercentageCoupon(int ratio) {
this.ratio = ratio;
}
@Override
public int calc(int productAmount) {
int discountAmount = (int)(productAmount * (double)ratio / 100);
return Math.max(productAmount - discountAmount, 0);
}
}
public class CouponService {
private CouponRepository couponRepository = new MockCouponRepository();
public Coupon getCoupon(long couponId) {
return couponRepository.findById(couponId)
.orElseThrow(RuntimeException::new);
}
}
import java.util.Optional;
public interface CouponRepository {
Optional<Coupon> findById(Long id);
}
import java.util.Optional;
public class MockCouponRepository implements CouponRepository {
@Override
public Optional<Coupon> findById(Long id) {
if (id <= 0)
return Optional.empty();
if (id < 100)
return Optional.of(new PercentageCoupon(10));
return Optional.of(new DiscountCoupon(2000));
}
}
public class Product {
private String name;
private int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public int discount(Coupon percentageCoupon) {
return percentageCoupon.calc(price);
}
}
반응형
'cs > java-spring-boot' 카테고리의 다른 글
[Zero-base] 11-11. 책임연쇄(Chain of responsibility) (0) | 2022.03.15 |
---|---|
[Zero-base] 11-10. 템플릿 메서드(Template Method) (0) | 2022.03.15 |
[Zero-base] 11-8. 프록시(Proxy) (0) | 2022.03.15 |
[Zero-base] 11-7. 데코레이터(Decorator) (0) | 2022.03.15 |
[Zero-base] 11-6. 파사드(Facade) (0) | 2022.03.15 |