728x90
728x90
전략 패턴(Strategy Pattern)
- 정책 패턴(Policy Pattern)이라고도 한다.
- 객체의 행위를 바꾸고 싶은 경우 '직접' 수정하지 않고, 전략이라고 부르는 '캡슐화한 알고리즘'을 컨텍스트 안에서 바꿔주면서 상호 교체가 가능하게 만드는 패턴

프로그래밍에서 컨텍스트는 상황, 맥락, 문맥을 의미하며, 개발자가 어떠한 작업을 완료하는 데 필요한 모든 관련 정보를 의미한다.
자바의 전략 패턴
- 우리가 어떤 것을 살 때, 네이버페이, 카카오페이 등 다양한 방법으로 결제하듯이, 어떤 아이템을 살 때
LUNACard
로 사는 것과KAKAOCard
로 살 수 있다. - 다음은 쇼핑 카트에 아이템을 담아
LUNACard
또는KAKAOCard
라는 2개의 전략으로 결제하는 코드이다.
import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; interface PaymentStrategy { public void pay(int amount); } class KAKAOcardStrategy implements PaymentStrategy { private String name; private String cardNumber; private String cvv; private String deteOfExpriy; public KAKAOCardStrategy(Strig nm, String ccNum, Strig cvv, String expriyDate) { this.name = nm; this.cardNumber = ccNum; this.cvv = cvv; this. dateOfExpry = expryDate; } @Override public void pay(int amount) { System.out.println(amout + " paid using KAKAOCard.") } } class LUNACardStrategy implements PaymentStrategy { private String emailId; private String password; public LUNACardStrategy(String email, String pwd) { this.emailId = email; this.password = pwd; } @Override public void pay(int amout) { System.out.println(amouut + "paid using LUNACard."); } } class Item { private String name; private int price; public Item(String name, Int cost) { this.name = name; this.price = cost; } public Stirng 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 calss HelloWorld { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart(); Item A = new Item("A", 100); Item B = new Item("B", 200); cart.addItem(A); cart.addItem(B); // pay by LUNACard cart.pay(new LUNACardStrategy("usr@ex.com", "pass1234")); // pay by KAKAOCard cart.pay(new KAKAOCardStrategy("Hong GillDong", "1111222233334444", "123", "12/34")); } } /* 400 paid using LUNAcard 400 paid usig KAKAOCard */
passport
의 전략 패턴
- 전략 패턴을 활용한 라이브러리로
passport
가 있다.
Passport.js
Simple, unobtrusive authentication for Node.js
www.passportjs.org
passport
는 Node.js에서 인증 모듈을 구현할 때 쓰는 미들웨어 라이브러리이며, 여러 가지 '전략'을 기반으로 인증할 수 있게 한다.- 서비스 내의 회원가입된 아이디와 비밀번호를 기반으로 인증하는
LocalStrategy
전략과 페이스북, 네이버 등 다른 서비스를 기반으로 인증하는OAuth
전략 등을 지원한다. - 다음 코드처럼 '전략'만 바꿔서 인증할 수 있다.
var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; passport.use(new LocalStrategy( function(username, password, done) { User.findOne({ username: username }, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Incorrect username.' }); } if (!user.validPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); }); } ));
passport.use(new LocalStrategy( ...
처럼passport.use()
라는 메서드에 '전략'을 매개변수로 넣어서 로직을 수행하는 것을 볼 수 있다.
참고 사이트
Strategy
The Strategy pattern lets you isolate the code, internal data, and dependencies of various algorithms from the rest of the code. Various clients get a simple interface to execute the algorithms and switch them at runtime. The Strategy pattern lets you do a
refactoring.guru
728x90
728x90
'Computer Science > 개념 정리' 카테고리의 다른 글
[CS 개념] 응집도(Cohesion)와 결합도(Coupling) (0) | 2025.03.08 |
---|---|
[CS 개념] 옵저버 패턴(Observer Pattern) (1) | 2023.06.13 |
[CS 개념] 팩토리 패턴(Factory Pattern) (1) | 2023.06.11 |
[CS 개념] 싱글톤 패턴(Singletone Pattern) (0) | 2023.05.18 |