전략 패턴
전략 패턴(strategy pattern) 또는 정책 패턴(policy pattern)은 실행 중에 알고리즘을 선택할 수 있게 하는 행위 소프트웨어 디자인 패턴이다. 전략 패턴은
- 특정한 계열의 알고리즘들을 정의하고
- 각 알고리즘을 캡슐화하며
- 이 알고리즘들을 해당 계열 안에서 상호 교체가 가능하게 만든다.
전략은 알고리즘을 사용하는 클라이언트와는 독립적으로 다양하게 만든다.[1] 전략은 유연하고 재사용 가능한 객체 지향 소프트웨어를 어떻게 설계하는지 기술하기 위해 디자인 패턴의 개념을 보급시킨 디자인 패턴(Gamma 등)이라는 영향력 있는 책에 포함된 패턴들 가운데 하나이다.
개요
[편집]전략[2] 디자인 패턴은 유연하고 재사용 가능한 객체 지향 소프트웨어를 설계하기 위해 반복되는 디자인 문제를 해결하는 방법, 즉 객체는 구현, 변경, 테스트, 재사용이 쉬워야 한다는 것을 기술하는, 잘 알려진 23가지 GoF 디자인 패턴들 중 하나이다.
구조
[편집]UML 클래스 및 시퀀스 다이어그램
[편집]
클래스 다이어그램
[편집]

예시
[편집]C#
[편집]다음은 C#의 예이다.
public class StrategyPatternWiki { public static void Main(String[] args) { Customer firstCustomer = new Customer(new NormalStrategy()); // Normal billing firstCustomer.Add(1.0, 1); // Start Happy Hour firstCustomer.Strategy = new HappyHourStrategy(); firstCustomer.Add(1.0, 2); // New Customer Customer secondCustomer = new Customer(new HappyHourStrategy()); secondCustomer.Add(0.8, 1); // The Customer pays firstCustomer.PrintBill(); // End Happy Hour secondCustomer.Strategy = new NormalStrategy(); secondCustomer.Add(1.3, 2); secondCustomer.Add(2.5, 1); secondCustomer.PrintBill(); } } class Customer { private IList<double> drinks; // Get/Set Strategy public IBillingStrategy Strategy { get; set; } public Customer(IBillingStrategy strategy) { this.drinks = new List<double>(); this.Strategy = strategy; } public void Add(double price, int quantity) { drinks.Add(Strategy.GetActPrice(price * quantity)); } // Payment of bill public void PrintBill() { double sum = 0; foreach (double i in drinks) { sum += i; } Console.WriteLine("Total due: " + sum); drinks.Clear(); } } interface IBillingStrategy { double GetActPrice(double rawPrice); } // Normal billing strategy (unchanged price) class NormalStrategy : IBillingStrategy { public double GetActPrice(double rawPrice) { return rawPrice; } } // Strategy for Happy hour (50% discount) class HappyHourStrategy : IBillingStrategy { public double GetActPrice(double rawPrice) { return rawPrice * 0.5; } }
같이 보기
[편집]각주
[편집]- ↑ Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates, Head First Design Patterns, First Edition, Chapter 1, Page 24, O'Reilly Media, Inc, 2004. ISBN 978-0-596-00712-6
- ↑ Erich Gamma; Richard Helm; Ralph Johnson; John Vlissides (1994). 《Design Patterns: Elements of Reusable Object-Oriented Software》. Addison Wesley. 315ff쪽. ISBN 0-201-63361-2.
- ↑ “The Strategy design pattern - Structure and Collaboration”. 《w3sDesign.com》. 2017년 8월 12일에 확인함.
외부 링크
[편집]위키미디어 공용에 전략 패턴 관련 미디어 분류가 있습니다.