티스토리 뷰
Strategy pattern
From Wikipedia, the free encyclopedia
In computer programming, the strategy pattern is a particular software design pattern, whereby algorithms can be selected on-the-fly at runtime.
In some programming languages, such as those without polymorphism, the issues addressed by this pattern are handled through forms of reflection, such as the native function pointer or function delegate syntax.
The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
Contents[hide] |
[edit] Diagram
[edit] Code Examples
[edit] C#
using System; namespace Wikipedia.Patterns.Strategy { // MainApp test application class MainApp { static void Main() { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyA()); context.Execute(); context = new Context(new ConcreteStrategyB()); context.Execute(); context = new Context(new ConcreteStrategyC()); context.Execute(); } } // The classes that implement a concrete strategy should implement this // The context class uses this to call the concrete strategy interface IStrategy { void Execute(); } // Implements the algorithm using the strategy interface class ConcreteStrategyA : IStrategy { public void Execute() { Console.WriteLine( "Called ConcreteStrategyA.Execute()" ); } } class ConcreteStrategyB : IStrategy { public void Execute() { Console.WriteLine( "Called ConcreteStrategyB.Execute()" ); } } class ConcreteStrategyC : IStrategy { public void Execute() { Console.WriteLine( "Called ConcreteStrategyC.Execute()" ); } } // Configured with a ConcreteStrategy object and maintains a reference to a Strategy object class Context { IStrategy strategy; // Constructor public Context(IStrategy strategy) { this.strategy = strategy; } public void Execute() { strategy.Execute(); } } }
[edit] Java
package wikipedia.patterns.strategy; // MainApp test application class MainApp { public static void main() { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyA()); context.execute(); context = new Context(new ConcreteStrategyB()); context.execute(); context = new Context(new ConcreteStrategyC()); context.execute(); } } // The classes that implement a concrete strategy should implement this // The context class uses this to call the concrete strategy interface IStrategy { void execute(); } // Implements the algorithm using the strategy interface class ConcreteStrategyA implements IStrategy { public void execute() { System.out.println( "Called ConcreteStrategyA.execute()" ); } } class ConcreteStrategyB implements IStrategy { public void execute() { System.out.println( "Called ConcreteStrategyB.execute()" ); } } class ConcreteStrategyC implements IStrategy { public void execute() { System.out.println( "Called ConcreteStrategyC.execute()" ); } } // Configured with a ConcreteStrategy object and maintains a reference to a Strategy object class Context { IStrategy strategy; // Constructor public Context(IStrategy strategy) { this.strategy = strategy; } public void execute() { strategy.execute(); } } }
[edit] Strategy versus Bridge
The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.
The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.
[edit] Strategy Pattern and OCP
According to Strategy pattern, the behaviours of a class should not be inherited, instead they should be encapsulated using interfaces. As an example, consider a car class. Two possible behaviours of car are brake and accelerate.
Since accelerate and brake behaviours change frequently between models, a common approach is to implement these behaviours in subclasses. This approach has significant drawbacks: accelerate and brake behaviours must be declared in each new Car model. This may not be a concern when there are only a small number of models, but the work of managing these behaviors increases greatly as the number of models increases, and requires code to be duplicated across models. Additionally, it is not easy to determine the exact nature of the behavior for each model without investigating the code in each.
The strategy pattern uses composition instead of inheritance. In the strategy pattern behaviours are defined as separate interfaces and abstract classes that implement these interfaces. Specific classes encapsulate these interfaces. This allows better decoupling between the behaviour and the class that uses the behaviour. The behaviour can be changed without breaking the classes that use it, and the classes can switch between behaviours by changing the specific implementation used without requiring any significant code changes. Behaviours can also be changed at run-time as well as at design-time. For instance, a car object’s brake behaviour can be changed from BrakeWithABS() to Brake() by changing the brakeBehaviour member to:
brakeBehaviour = new Brake();
This gives greater flexibility in design and is in harmony with OCP (Open Closed Principle) that states classes should be open for extension but closed for modification.
[edit] See also
- Mixin
- Policy-based design
- First-class function
- Template method pattern
- Bridge pattern
- Open/closed principle
[edit] External links
- Description by Vince Huston
- Strategy Pattern for Java article
- Data & object factory
- Refactoring: Replace Type Code with State/Strategy
scope/Purpose | Creational | Structural | Behavioral |
---|---|---|---|
Class | Factory Method | Adapter | Interpreter |
Class | Template Method | ||
Object | Abstract Factory | Adapter | Chain of Responsibility |
Object | Factory | Bridge | Command |
Object | Builder | Composite | Iterator |
Object | Prototype | Decorator | Mediator |
Object | Singleton | Facade | Memento |
Object | Flyweight | Observer | |
Object | Proxy | State | |
Object | Strategy | ||
Object | Visitor |
'IT > 프로그래밍' 카테고리의 다른 글
Java Guide - Polymorphism (0) | 2007.07.31 |
---|---|
Java Guide - Polymorphism (0) | 2007.07.31 |
[DesignPattern] Strategy Pattern (스트래티지 패턴) (0) | 2007.07.31 |
윈도우 메시지 후킹 강좌 (첨 해보는 사람들을 위해서) 이은규 / unkyulee (0) | 2007.07.19 |
Pthread API Reference (0) | 2007.07.06 |
- Total
- Today
- Yesterday
- 지루박멸연구센타
- 열정의 힘을 믿는다
- Le4rN TO Cr4cK
- 디버깅에관한모든것(DebugLab)
- sysinternals
- FoundStone
- hashtab
- 보안-coderant
- 디바이스드라이버 개발자 포럼
- dualpage.muz.ro
- osronline.com - 드라이버 관련 정보 사이트
- NtInternals - NativeAPI Refere…
- pcthreat - spyware 정보 제공
- rootkit.com - 루트킷 관련 정보
- www.ntinternals.net
- WINE CrossRef. - source.winehq…
- tuts4you
- hex-rays
- idapalace
- idefense
- immunityinc
- threatexpert
- hdp.null2root.org
- www.crackstore.com
- crackmes.de
- www.who.is
- www.cracklab.ru
- community.reverse-engineering.…
- video.reverse-engineering.net
- SnD
- 클레이 키위
- reversengineering.wordpress.co…
- www.openrce.org
- www.woodmann.com
- PEID.Plusins.BobSoft
- roxik.com/pictaps/
- regexlib.com
- spyware-browser.com
- www.usboffice.kr
- regulator
- www.txt2re.com
- ietab.mozdev.org
- zesrever.xstone.org
- www.heaventools.com/PE-file-he…
- www.heaventools.com
- www.innomp3.com
- 울지않는벌새
- exetools.com-forum
- exetools.com
- utf8 conv
- robtex - IP trace
- onsamehost - same IP sites
- JpopSuki
- jsunpack.jeek.org
- wepawet.iseclab.org
- www.jswiff.com
- www.hackeroo.com
- winesearcher.co.kr
- khpga.org
- malwareurl.com
- anubis.iseclab.org
- www.crummy.com-eautifulSoup
- malwarebytes.org/forums
- bbs.janmeng.com
- blackip.ustc.edu.cn
- eureka.cyber-ta.org
- exploit-db.com
- PIR
- 군함도
- 사회간접자본
- ElasticSearch
- 맥쿼리인프라
- 주식트래이딩
- 미국주식
- 레고랜드
- 시스템트래이딩
- ubuntu
- 주식
- 매매가격지수
- 주택구매력지수
- SBI저축은행
- systemd
- 다올저축은행
- INVOICE
- CriticalSection
- 피봇
- 신한저축은행
- Pivot
- logrotate
- 자동트래이딩
- hai
- 전세매매지수
- 공공인프라
- ChatGPT
- 실시간트래이딩
- O365
- ROA
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |