Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
Tags
- 코딩테스트
- mysql
- 백준 16927
- 프로그래머스 숫자의 표현 java
- 프로그래머스 네트워크 java
- 백준 17425
- 네트워크
- Codility
- Arrays
- time complexity
- 백준 14391
- Algorithm
- 백준 11723
- 프로그래머스 도둑질 java
- Math.floor()
- 프로그래머스 연속된 수의 합 java
- 자바
- java 내림
- 백준 4375
- 백준 16935
- 백준 15661
- java
- java 반올림
- sort
- java 올림
- Math.ceil()
- 프로그래머스 옹알이 java
- 0으로 채우기
- 백준 18290
- 알고리즘
Archives
- Today
- Total
취미처럼
[DP] 전략 패턴 본문
전략 패턴(strategy pattern)
객체의 행위를 바꾸고 싶은 경우 직접 수정하지 않고 전략이라고 부르는 캡슐화한 알고리즘을 컨텍스트 안에서 바꿔주면서 상호 교체가 가능하게 만드는 패턴
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
interface PaymentStrategy {
public void pay(int amount);
}
class CardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CardStrategy(String nm, String ccNum, String cvv, String expiryDate){
this.name=nm;
this.cardNumber=ccNum;
this.cvv=cvv;
this.dateOfExpiry=expiryDate;
}
@Override
public void pay(int amount) {
System.out.println(amount +" paid Card");
}
}
class CashStrategy implements PaymentStrategy {
private String emailId;
private String password;
public CashStrategy(String email, String pwd){
this.emailId=email;
this.password=pwd;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid Cash.");
}
}
class Item {
private String name;
private int price;
public Item(String name, int cost){
this.name=name;
this.price=cost;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
class ShoppingCart {
List<Item> items;
public ShoppingCart(){
this.items=new ArrayList<Item>();
}
public void addItem(Item item){
this.items.add(item);
}
public void removeItem(Item item){
this.items.remove(item);
}
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
public void pay(PaymentStrategy paymentMethod){
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
public class Main{
public static void main(String []args){
ShoppingCart cart = new ShoppingCart();
Item A = new Item("apple",100);
Item B = new Item("banana",200);
cart.addItem(A);
cart.addItem(B);
// pay by Cash
cart.pay(new CashStrategy("test@google.com", "1234"));
// pay by Card
cart.pay(new CardStrategy("yujin", "123456789", "123", "23/01"));
}
}
'Design Pattern' 카테고리의 다른 글
[DP] 프록시 패턴 (0) | 2021.03.19 |
---|---|
[DP] 옵저버 패턴 (0) | 2021.03.19 |
[DP] 팩토리 패턴 (0) | 2021.03.19 |
[DP] 싱글톤 패턴 (0) | 2021.03.19 |
[DP] DIP (0) | 2021.03.19 |
Comments