Strategy Pattern
Last updated
Last updated
코드 중복 방지 즉 달라지는 부분을 찾고 분리해 낸다.
Runtime 시 target method 변경
확장성 및 알고리즘 변경 용이
public interface Pay {
void action();
}
public class KakaoPayService implements Pay{
@Override
public void action() {
System.out.println("카카오페이로 지불합니다.");
}
}
public class NaverPayService implements Pay {
@Override
public void action() {
System.out.println("네이버페이로 지불합니다.");
}
}
public class WechatPayService implements Pay {
@Override
public void action() {
System.out.println("위챗페이로 지불합니다.");
}
}
public class BuyItem {
private Pay pay ;
public BuyItem(Pay pay){
this.pay = pay;
}
public void payAction(){
pay.action();
}
public void setPay(Pay pay){
this.pay = pay;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("======지불 해보겠습니다!");
BuyItem buyItem = new BuyItem(new KakaoPayService());
buyItem.payAction();
BuyItem buyItem2 = new BuyItem(new NaverPayService());
buyItem2.payAction();
BuyItem buyItem3 = new BuyItem(new WechatPayService());
buyItem3.payAction();
}
}